skip to Main Content

I don’t want to refetch the query because if the data is not stale it’s still refetching it with refetch() function. And also if I add condition like isStale == true then it will refetch but even if I remain on the same screen it will continously refetching it after stale is true

I just want it to work like it works on web useQuery will run on every component render

  const { status, isFetching, isPending, isError, isStale, data, error, isFetched, refetch } = useQuery({
    queryKey: ['brands'],
    queryFn: getBrands,
    staleTime: 10000,
  });

  useFocusEffect(
    useCallback(() => {
      console.log(isStale);
      if (isStale === true) {
        refetch();
      }
    }, [isStale]),
  );

3

Answers


  1. Chosen as BEST ANSWER

    I solved it using useIsFocused hook of react navigation and react query enabled condition. Now the useQuery will not refetch everytime I focus on screen rather just run means if you use staletime and you have fresh data it will not refetch and just display from fresh data

    import { useIsFocused } from '@react-navigation/native';
    
    const isFocused = useIsFocused();
    
    const { status, isFetching, data, error, isError } = useQuery({
        queryKey: ['brands'],
        queryFn: getBrands,
        enabled: isFocused,
        retry: false,
    });
    

  2. You’re using the wrong option. If you want the data to refetch after X milliseconds then you should not specify staleTime: X. Instead you should be specifying refetchInterval: X. In any-case, you don’t want the fetching operation tied to your react render cycles.

    Login or Signup to reply.
  3. If you want the useQuery hook to behave more like it does on the web, where it runs on every component render, you can achieve this in React Native by triggering a refetch whenever the component mounts or updates. You can do this by using the useEffect hook instead of useFocusEffect.
    Here’s how you can modify your code:

    import React, { useEffect } from 'react';
    import { useQuery } from 'react-query';
    
    const YourComponent = () => {
      const { status, isStale, data, refetch } = useQuery({
        queryKey: ['brands'],
        queryFn: getBrands,
        staleTime: 10000,
      });
    
      useEffect(() => {
        if (status === 'success' && isStale) {
          refetch();
        }
      }, [status, isStale, refetch]);
    
      return (
        <div>
          {/* Your component CODE */}
        </div>
      );
    };
    
    export default YourComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search