apollographql / apollo-client

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
https://apollographql.com/client
MIT License
19.32k stars 2.65k forks source link

`cache-only` fetchPolicy results in network request after deleting cached data #11997

Open mogzol opened 1 month ago

mogzol commented 1 month ago

Issue Description

When using the cache-only fetch policy with useQuery, if data is cleared from the cache in a client.refetchQueries operation, the query will make a network request, even though that should never happen with a cache-only fetch policy.

Link to Reproduction

https://codesandbox.io/p/sandbox/apollo-cache-policy-issue-dj2w8s

Reproduction Steps

@apollo/client version

3.11.4

alessbell commented 1 month ago

Hi @mogzol 👋

Thanks for opening this issue. We agree this is surprising behavior, and we're looking at changing this in Apollo Client 4.0, currently in the planning stage, to eliminate the possibility of a query with a fetch policy of cache-only of ever going to the network.

In the meantime, you can leverage onQueryUpdated which is described in the "refetching selectively" section of our docs to prevent the network request:

async function refetch() {
  await client.refetchQueries({
+    onQueryUpdated(observableQuery) {
+      return observableQuery.options.fetchPolicy !== "cache-only";
+    },
    updateCache(cache) {
      cache.modify({
        id: "ROOT_QUERY",
        fields: { user: (_, { DELETE }) => DELETE },
      });
    },
  });
}