Search code examples
reactjscachingpollingreact-querycache-invalidation

Update cache of periodical react-query with refetchInterval from other place


For a counter I am polling the backend periodically with react-query using the refetchInterval option:

const { items } = useQuery(
  ["queryKey"],
  requestFn,
  {
    refetchInterval: 5000,
  }
);
...
<Counter>{items.length}</Counter>

Alas, when I add or delete an item, it takes up to 5 seconds to be reflected in the counter.

How can I force the counter to update immediatly?

I thought of triggering the query with the same key once after the add/deletion routine, but it doesn't work.

addItem().then(() => useQuery(
  ["queryKey"],
  requestFn,
))

Solution

  • You'd likely want to do queryClient.invalidateQueries(["queryKey"]) after running the mutation, because that will re-fetch new data right away. This is documented here: https://tanstack.com/query/v4/docs/guides/invalidations-from-mutations