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
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
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 specifyingrefetchInterval: X
. In any-case, you don’t want the fetching operation tied to your react render cycles.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: