reactjsreact-querytanstackreact-query

How to not fetch cached data in react-query?


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


Solution

  • 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.