-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Description
After displaying a list (data coming from a query), a component use a mutation to post some new data that would go to this list. After mutation succeed, I invalidate the query cache (multiple techniques were tried, with different and most of the time expected results, see below) concerning the queries, then push back the list on to history.
The techniques I used to invalidate the cache are the following:
- refetchQueries (as the docs suggest).
await queryCache.refetchQueries(["items"]);
- refetchQueries with
{force: true}
await queryCache.refetchQueries(["items"], {force: true});
- removeQueries
await queryCache.removeQueries(["items"]);
- set queries as stale so the next render will actually fetch the data
queryCache.getQueries(["items"]).forEach((query) => {
query.state.isStale = true;
});
With default configuration, every method works (with slightly different but expected behaviors).
With react-query configured to use a non-default staleTime though, only 2, 3 and 4 works, as refetchQueries (and more specifically the fetch method on the query will ignore non-stale queries if not forced.
Although after reading the code I understand this is the expected behavior, I think there are a few defects :
- Documentation states that after a mutation, you can refetch your data using
refetchQueriesand suggest to do so. It makes it hard to debug as there are no pointers to what can make the refetching not happen. - Although refetching is great, in some case it may be more correct to just set the queries as stale and let the app refetch the data itself whenever a component uses one of the queries (aka method 4). In some cases (ok, including mine), one mutation could invalidate a bunch of queries, while the immediate need for the next user view is probably only one of those queries. Making the query stale makes it easier for the developper which does not have to know the logic of "what next page will need". We stale a bunch of queries, then mutate history,
react-querydoes the rest (with old data shown while refetching). Refetching all queries related may be a bit too much, most of them may be never used again. Would it be possible to add an api method toqueryCachetosetQueriesAsStale(or whatever english describes this best) ? Then it could be shown as an alternative to refetch in documentation once mutation is done.
I can work on a patch (code, tests and doc) if this makes sense.