0

I have a query that fetches some data in a date range, I recently moved from doing it myself to using react-query and am stuck on the cache logic. What I want is if this date range was fetched once, it gives me the data, else it fetches the data and of course save it with the current date range

I tried this

    const { data, isFetching} = useQuery({
        queryKey: ["key1", startDate, endDate],
        queryFn: () => getData(startDate, endDate),
        initialData: [],
    });

which got me what I wanted but also not, my problem here is when I'm looking at the network tab I can see on the first load it fetches the data, Perfect. then I change to another date range and it fetches this data, also Perfect. but then I go back to the first date range and I can see the old data displayed directly, BUT i see a request on the network tab for it.

How can I stop that! it's also causing me trouble because I use isFetching to display some loading overlay, so even though I can clearly see the data is plotted already i still have to wait through it, and finally the API call is a bit expensive on the server so i don't wanna fetch if I already have the cache

1 Answer 1

1

I think you can achieve that by using the ensureQueryData function. I've found this example in the docs:

const data = await queryClient.ensureQueryData({ queryKey, queryFn })

This way you first check on cache for the given key, and if nothing is found it runs the function and returns the result.

Another option could be to by making a custom hook use getQueryData to read the cache and if nothing is found it will return undefined so you could manage to call to your api but I think that should work out of the box and achieve the same.

This is the link to the whole documentation.

4
  • First of all thanks a lot for your answer, secondly I got a bit lost in the docs, when i want to fetch something in my code i use the hook useQuery, how can i access the queryClient. do i just import it and directly use it, won't that be "conflicting" with the default options i set on the provider at the app file Commented Jun 16 at 17:02
  • 1
    here I've prepared you a small example: stackblitz.com/edit/… when clicking for the first time on the different characters a request is made to the api but the second time you click on the same character we read cache's data. I use queryClient.ensureQueryData alongside useQuery using the same queryKey to load the existing data that may be available in the cache in case there's none we fetch it from the api as usual. I've also configured cache staleTime: Infinity to last forever but you should adjust it to your needs.
    – jcobo1
    Commented Jun 16 at 19:01
  • ignore the wrong tsconfig in my project :)
    – jcobo1
    Commented Jun 16 at 19:02
  • 1
    Thanks a lot, that wraps it very nicely Commented Jun 17 at 1:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.