I have prepared a simple demo with react-router-dom 6 and react query. I have a couple of routes and a fetch call that takes place on the first route (Home). What I want to achieve is navigating to the About page or any other page and do not perform another request for a certain time period (maybe never again) but if I refresh the page I want to be able to re trigger the request to get the data.
I have tried using staleTime
when but if I refresh the page I get no results, just a blank page. refreshInterval
works on refresh but does not keep the data when I change routes.
I have also tried this pattern in this article but still I don't get the job done.
Probably it may be that something I don't understand but the question is how do I avoid making the same request over and over again, perfrm it only once but still being able to get the data if I refresh the page when navigating between different routes.
The solution to the problem came from one of the maintainers on the official github repo eventually and is related to adding placeholderData
as an empty array instead of initialData
and setting staleTime
to Infinity in my case as I only want to perform the request once.
Setting placeholderData
gives you the opportunity to show some dummy data normally until you fetch the real but in my case it seems to do the job. More to read regarding this at this source
const { isFetching, data: catImages } = useQuery({
queryKey: ["catImages"],
queryFn: getCatImages,
placeholderData: [],
staleTime: Infinity
});