Let’s say I have a useQuery
with the following fetch policies:
const { loading, data } = useQuery(GET_CATEGORIES, {
fetchPolicy: "cache-and-network",
nextFetchPolicy: "cache-first",
});
Somewhere else in the code I remove the query’s only queried field with cache.evict
:
cache.evict({ fieldName: "categories" });
cache.gc();
Because I’m deleting the entry from the cache, I expect the hook to trigger a render with { data: undefined }
, but this is not what happens.
- If I leave the code as-as, the query is silently refetched without re-render (unless the server returns different data).
- If I add
notifyOnNetworkStatusChange: true
, thenloading
will be set totrue
butdata
will still be defined.
I also tried the following ways of evicting the data:
// Behaves the same way as the `cache.evict` call above:
cache.modify({
fields: { categories: (_, { DELETE }) => DELETE },
});
// Behaves the same way, except I get `networkStatus: NetworkStatus.refetch`
// instead of `loading: true`
client.refetchQueries({
updateCache(cache) {
cache.evict({ fieldName: "categories" });
},
});
And I’ve read the following threads on this topic:
https://github.com/apollographql/apollo-client/issues/7300
https://github.com/apollographql/apollo-client/issues/7060
My questions are:
- Is this intended behavior or is this a bug?
- How can achieve what I want — delete data from the cache and have
data
set toundefined
until it’s fetched again from the network?
Link to play around with this issue:
https://codesandbox.io/p/devbox/apollo-cache-eviction-test-4nd2s9