4

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?

1
  • 🚨 The basic correction is use new QueryClient() ounce in app (App.js) 🚨 use useQueryClient() in other part of app to use same instance to update object Commented May 14, 2023 at 17:24

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Apparently is not updating the data. I have the same issue. The only solution I found is to invalidate the current data. @TkDodo
show a codesandbox reproduction please
2

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

Comments

0

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
  },
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.