Restore API does not retain ROOT_QUERY, ROOT_MUTATION
See original GitHub issueIntended outcome:
Calling cache.gc()
after the cache is restored using a tool like https://github.com/apollographql/apollo-cache-persist should not remove all entities in the cache and only remove unreachable entities.
Actual outcome:
Calling cache.gc()
after the cache is restored using a tool like https://github.com/apollographql/apollo-cache-persist removes all entities in the cache.
Explanation
It looks like this happens because when you call cache.restore(data)
as defined here: https://github.com/apollographql/apollo-client/blob/master/src/cache/inmemory/inMemoryCache.ts#L99
and subsequently call EntityStore replace: https://github.com/apollographql/apollo-client/blob/master/src/cache/inmemory/entityStore.ts#L238
it hydrates the cache, but never calls retain
on any ID. Normally, the ROOT_QUERY
is retained by a write to the store: https://github.com/apollographql/apollo-client/blob/master/src/cache/inmemory/writeToStore.ts#L114:L114
but if nothing has been written to the store yet, and gc
is called immediately after a cache.restore
using a tool like cache-persist, then there are no rootIds
retained and the entire cache will get garbage collected.
I think the solution would be to either:
- Default the rootIds to include
ROOT_QUERY
andROOT_MUTATION
on cache instantiation so that they are not lazily retained on a call towriteToStore
but assumed to be desired to be retained by default - Retain
ROOT_QUERY
andROOT_MUTATION
if a call tocache.restore
includes those keys at the time restore is called - Have downstream tools like cache-persist know that after doing a restore, they will need to retain IDs they care about like
ROOT_QUERY
andROOT_MUTATION
. I think this is a riskier approach, because as a user I would assume that ROOT_QUERY should be retained by default based on the documentation ofcache.gc()
:
I think rootIds
is not a familiar term to most folks in these docs and they’d assume that unreachable would mean that there are things like dangling normalized entities, not potentially the ROOT_QUERY itself.
Let me know what your thoughts are, thanks!
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
@benjamn Genius, I was indeed importing
getDataFromTree
from@apollo/react-ssr
. I switched the import to@apollo/client/react/ssr
and it’s working properly with newer versions (now3.3.6
)Thanks so much and sorry for the distraction!
@loteoo If you’re not calling
cache.gc()
in that code, this issue (#7323) probably isn’t the cause of your problems, but getting an empty object is definitely strange/worrisome!A couple more questions:
getDataFromTree
from@apollo/client/react/ssr
?ApolloProvider
from@apollo/client
(or@apollo/client/react/context
)?The older
@apollo/react-*
packages should no longer be used.