Backdrop: I'm developing a React
application using Apollo
to query a GraphQL
backend, a standard InMemoryCache
and GraphQL codegen
to generate typescript hooks for queries and mutations.
In some cases I am using refetchQueries
to make sure cache is invalidated when a mutation is done. This does work as expected, but only as long as there is a currently mounted React component in the DOM that uses this query.
An example is where I have a list of entities rendered in the application and then move to a different route, at which point the list component unmounts. I then execute a mutation from the other route, and when when returning to the list page it shows outdated data even if the listing query was passed into the refetchQueries
array on the mutation.
I do understand that it does not make sense to instantly refetch data for components that are not mounted, because they may never be mounted again, but I do find it strange that when the component is later remounted it uses the outdated cache instead of going to the server to refetch it.
I would guess there should be some kind of "refetch when mounted" logic, but I cannot find this. Am I missing something?
I do also know that you can manually normalize the cache, but that just does not make sense for all cases, and sometimes you would prefer to refetch when there is a complex data model with many references to other entities that may have also been changed during the same mutation.
Side note: I've tried to cover for this issue by changing the fetchingPolicy on the said query to be "cache-and-network", having an expectation that my component would then first render with the old and outdated cache data, and then being replaced with the new data as soon as the data comes back from the server. This does however not happen, and as soon as I set "cache-and-network" the query starts acting like "no-cache" instead. When the component remounts it is never rendered with the cached data even if there has been no mutation and the query has the exact same arguments.
I'm puzzled here, and would very much like some one to help shed some light on this, as I find it crucial to fully understand how these concepts work, and if any of it could actually be a bug in apollo.
Relevant versions:
"@apollo/client": "^3.5.6",
"@graphql-codegen/typescript-react-apollo": "^3.3.2",
"graphql": "^16.1.0",
"react": "^17.0.2",