React-native : Stop an automatic refetch when screen is unmounted

Viewed 755

I am using React-native and React-query and I want stop the automatic refetch when the screen is unmounted.

Currently, when I go to my target screen, I call a query with an interval parameter :

const { data: mission } = useMissionFetcher(missionSelectedId, 5000)

useMissionFetcher :

export const useMissionFetcher = (idMission: string, interval: number): QueryResult<MissionMobile> => {
    const missionsQueryFn = () => getMission(idMission)
        return useQuery([QueryKeys.mission, idMission], missionsQueryFn, {
          ...baseReactQueryConfig,
          refetchInterval: interval,
        })
  }

baseReactQueryConfig :

export const baseReactQueryConfig = {
    refetchOnWindowFocus: false,
    staleTime: Infinity,

How can I do to stop this refetch when I quit the screen ?

3 Answers

I think that you use navigate to get out of your current screen , and that does not unMount the screen it. Use navigation.replace and your react query refetch will automatically stop , since it will be garbaged ( or unMount if you prefer)

In case u want to refetch only when you focus your screen because a lot of people want to do this I think u can juste use this hook

export const useRefetchOnFocus = (refetch = () => {}, canRefetch = true) => {
  const [isScreenFocused, setIsScreenFocused] = useState(false);
  useFocusEffect(() => {
    setIsScreenFocused(true); // when i focus the screen
    return () => setIsScreenFocused(false); // when i quit the screen
  });

  /* the screen still always active in cache so we need to check that the screen is focused in a use effect
  to dispatch the refetch only one time to avoid the infinity loop*/
  useEffect(() => {
    if (isScreenFocused && canRefetch) {
      refetch();
    }
  }, [canRefetch, isScreenFocused, refetch]);
};

and in your screen

  const { data, refetch } = useAccount();

  useRefetchOnFocus(refetch);
Related