Implementing Manual Control Over Refetch on Reconnect
Illustrate how to manually control the behavior of React Query when the network state changes from offline to online, including prompting the user before resuming data fetching.
import { useEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import NetInfo from '@react-native-community/netinfo';
Imports necessary hooks from React Query and the NetInfo library for network status detection.
function useManualRefetchOnReconnect() {
const queryClient = useQueryClient();
useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
if (state.isConnected) {
// Prompt the user before refetching the data
const userWantsToUpdate = confirm('Network is back. Refresh data?');
if (userWantsToUpdate) {
queryClient.refetchQueries();
}
}
});
return () => unsubscribe();
}, [queryClient]);
}
Defines a custom hook that listens to network changes. When the network becomes connected, it prompts the user to refresh data. If the user agrees, all queries are refetched.
export default useManualRefetchOnReconnect;
Exports the custom hook for use in the React components.