react query refetches with old query

Viewed 35

I have a list component that uses react-query to fetch the list data (in this case tickets)

<List
   fetch={{
     route: "tickets",
     queryKey: "tickets"
   }}
...
/>

The component fetches the data like so

const { isLoading, isError, data, refetch } = useQuery([queryKey], () => {
    return fetchEntity({ route: `${route}${window.location.search}` })
})

fetchEntity does nothing else than using axios to fetch an return the data

I'm also providing window.location.search to the route because I have a filter component that sets the filter to the url.

The filter works, but when I refetch (by refocusing the window), there are 2 different requests in the network tab.

queries

One with the filter params and the other one without the filter params. Therefore, the list shows the unfiltered data for a few milliseconds and then the filtered data again.

I also tried to use the query like so

const { isLoading, isError, data, refetch } = useQuery([queryKey, window.location.search], () => {
     return fetchEntity({ route: `${route}${window.location.search}` })
})

This fixed the problem where the unfiltered data was shown for a few milliseconds. However, the old data is still fetched (maybe it is just faster now so not visible in the ui?).

Can anyone explain this behaviour of react query?

1 Answers

The problem was I was fetching with the same query key in a child component. That's why I had multiple requests.

Related