T
TanStack3y ago
constant-blue

Invalidate pagination cache when something changed

Lets say you have a paginated list of todos, ordered by last created and descends
const [page, setPage] = React.useState(1);
const query = useQuery({
queryFn: () => fetch("/todo?page="+page),
queryKey: ["todos", page],
keepPreviousData: true
});
const [page, setPage] = React.useState(1);
const query = useQuery({
queryFn: () => fetch("/todo?page="+page),
queryKey: ["todos", page],
keepPreviousData: true
});
As you're clicking through the pages, a new todo is added on the server. So now all the cached data from all pages is wrong, because everything is shifted by 1 (due to the addition). How can I manually invalidate all the cache keys in this situation? Something like if cached data didn't match the result of the fetched data, invalidate all the other cache keys
1 Reply
optimistic-gold
optimistic-gold3y ago
the recommended way is to call queryClient.invalidateQueries in your queryFn after you've performed the check. the strategy is similar to: https://tkdodo.eu/blog/seeding-the-query-cache#seeding-details-from-lists
Seeding the Query Cache
With suspense for data fetching on the horizon, it is now more important than ever to make sure your cache is seeded properly to avoid fetch waterfalls.

Did you find this page helpful?