Waiting for queries to become stale before they are fetched again doesn't always work, especially when you know for a fact that a query's data is out of date because of something the user has done. For that purpose, the
QueryClient has an
invalidateQueries method that lets you intelligently mark queries as stale and potentially refetch them too!
Note: Where other libraries that use normalized caches would attempt to update local queries with the new data either imperatively or via schema inference, Svelte Query gives you the tools to avoid the manual labor that comes with maintaining normalized caches and instead prescribes targeted invalidation, background-refetching and ultimately atomic updates.
When a query is invalidated with
invalidateQueries, two things happen:
staleTimeconfigurations being used in
useQueryor related hooks
useQueryor related hooks, it will also be refetched in the background
When using APIs like
removeQueries (and others that support partial query matching), you can match multiple queries by their prefix, or get really specific and match an exact query. For information on the types of filters, you can use, please see Query Filters.
In this example, we can use the
todos prefix to invalidate any queries that start with
todos in their query key:
You can even invalidate queries with specific variables by passing a more specific query key to the
invalidateQueries API is very flexible, so even if you want to only invalidate
todos queries that don't have any more variables or subkeys, you can pass an
exact: true option to the
If you find yourself wanting even more granularity, you can pass a predicate function to the
invalidateQueries method. This function will receive each
Query instance from the query cache and allow you to return
false for whether you want to invalidate that query: