Caching api response when changing routes but be able to receive data when reloading the page #4965
-
I have asked a question in StackOverflow but so far no answers. I will apreciate if someone answers. I write the question as it is on SO. 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, perform it only once but still being able to get the data if I refresh the page when navigating between different routes. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
tl;dr Replace
By setting Hope that clarifies things. |
Beta Was this translation helpful? Give feedback.
-
Thanks a lot for the answer. I added that and it worked. Only thing that I noticed from my unit tests is that |
Beta Was this translation helpful? Give feedback.
-
There is a great resources about this here: https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query I encourage you to read the whole blog about reac-query. It will explain a lot. |
Beta Was this translation helpful? Give feedback.
tl;dr Replace
initialData
withplaceholderData
and addstaleTime
.initialData
is treated as you have the valid data for that query andstaleTime
is calculated from the last fetch, but initial fetch would not happend ifinitialData
andstaleTime
is set.You are hinting that you have valid data for that query and it should be valid for
staleTime
.By setting
placeholderData
you are hinting that it should be rendered initially, but you do not have any valid data for it, so initial fetch would be triggered.Hope that clarifies things.