I have a very basic app where I'm trying to fetch some data, and update the cache. For example purposes I tried to update the data to an empty array, but on the dev tools and the console logs I keep getting the old data
function App() {
const queryClient = new QueryClient();
const { isLoading, error, data } = useQuery('repoData', fetcher, {
onSuccess: (data) => {
queryClient.setQueryData('repoData', () => []);
},
});
console.log('data', data);
return (
<div className="App">
<Home />
</div>
);
}
what would be the correct way to update the cache?
Why would you want to update the cache of the same item you have just successfully fetched? React-Query will put the result of the fetcher into the data field returned from useQuery - you don’t need to do anything in onSuccess for that
That's is an example from official documentation.
const queryClient = useQueryClient()
const mutation = useMutation(editTodo, {
onSuccess: data => {
queryClient.setQueryData(['todo', { id: 5 }], data)
}
})
mutation.mutate({
id: 5,
name: 'Do the laundry',
})
// The query below will be updated with the response from the
// successful mutation
const { status, data, error } = useQuery(['todo', { id: 5 }], fetchTodoById)
https://react-query.tanstack.com/guides/updates-from-mutation-responses
The data resolved from your fetcher function will populate the cache from react-query with your chosen query key.
This data is available when destructuring the useQuery hook or is available with the onSuccess callback.
It can be usefull to manually update the data as shown here: https://stackoverflow.com/a/68949327/1934484
// fetcher function
function getProducts() {
// http call
const { data } = await http.get<{ products: ProductT[] }>(/products);
return data.products;
}
// data returned will be an array of products
const { data } = useQuery('products', getProducts, {
onSuccess: (data) => {
// data returned will be an array of products
},
});