I am using react query to fetch a list of items. After creating a new item, I am calling refetch
on my query to get the updated list. I see a new api call is made, and the new item I just created is returned as part of the api response. However, react-query is not updating its data value.
My code has a useQuery
wrapped in a hook to be able to be used in multiple places, as the query fn and its dependencies are complex:
// simplified version of the useQuery:
export const useItemsQuery = (search = "") => {
const { user } = usePermissions();
const filter = useStore((state) => state.projects.filter);
const projects = useQuery({
queryKey: [
"Items list",
`Items by ${filter}`,
`User: ${user.id}`
],
queryFn: () => complexQueryFunction(filter, user.id)
});
return projects;
};
In a few other components
// Component 1
const items = useItemsQuery()
items.data.map(...etc)
// Component 2
const items = useItemsQuery()
items.data.find(...etc)
The most confounding this is that even if I do into my react-query devtools and manually click "invalidate", the api call is made, and a new list is fetched. I can see that the data in the api call does not match the data in the react query devtools:
In the api call, 10 items:
In the react query devtools, where I clicked "invalidate" that caused the above api call, 9 items:
I find it bizarre that not only calling refetch
or queryClient.invalidateQuery({queryKey: [<the query key>]})
calls the api correctly and gets new data, but using the actual react-query devtools calls the api and gets the new data, but the data in reat-query's cache is not updated.
What might be causing this? Someone mentioned in another question that if you had mutated the data directly in place, react-query will not work properly and not update the cache. I checked my code and I don't believe this is the case. What else might be causing react-query to not update its .data
to the value coming from the network call?
complexQueryFunction
do? Do you have a wronguseMemo
somewhere in your component with missing dependencies?queryClient.resetQueries({ queryKey: ["Items list"] })
- with that, the api is called and the query cache is updated with the new data. My complexQueryFunction is only complex because of the way it builds params to call the api. Its not the component that is the issue, but rather something that is causing react-query to not update the.data
to the latest api response data