Apollo Client: Keep/Reset defaults on clearing or resetting store

832 Views Asked by At

I'm using apollo-link-state for locally storing errors, but I get the following error after clearing cache.

I've set the default value of errors to an empty array [] in apollo client configuration options.

However, after apolloClient.cache.reset() or apolloClient.store.reset(), it seems that I lose all default values, causing this error:

Error

Any ideas how to resolve this issue?

2

There are 2 best solutions below

1
On BEST ANSWER

From the docs:

Sometimes you may need to reset the store in your application, for example when a user logs out. If you call client.resetStore anywhere in your application, you will need to write your defaults to the store again. apollo-link-state exposes a writeDefaults function for you. To register your callback to Apollo Client, call client.onResetStore and pass in writeDefaults.

So you can do something like:

const cache = new InMemoryCache()
const link = withClientState({ cache, resolvers, defaults })

const client = new ApolloClient({
  cache,
  link,
})

client.onResetStore(stateLink.writeDefaults)
0
On

With Apollo 2.x, you can just do below:

cache.writeData({data : defaultData });

client.onResetStore(() => {
  cache.writeData({data : defaultData });
});

Assuming that you have a default data for cache set up above this code.