I need to set my Apollo Client Cache to its defaults

1.4k Views Asked by At

I have a React app which is using Apollo Client. I'm using apollo-link-state and apollo-cache-persist and need to reset my store to its default values when client.resetStore() is called in my app.

The docs say that when creating a client you should call client.onResetStore(stateLink.writeDefaults) and this will do the job but writeDefaults is exposed by Apollo Link State which i don't have direct access to as I’m using Apollo Boost.

Here is my Apollo Client code:

import ApolloClient from 'apollo-boost';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { persistCache } from 'apollo-cache-persist';
import { defaults, resolvers } from "./store";

const cache = new InMemoryCache();

persistCache({
  storage: window.localStorage,
  debug: process.env.NODE_ENV !== 'production',
  cache
});

const client = new ApolloClient({
  uri: process.env.NODE_ENV === 'production' ? 'https://five-yards-api.herokuapp.com/graphql' : 'http://localhost:7777/graphql',
  credentials: 'include',
  clientState: {
    defaults,
    resolvers
  },
  cache
});

// TODO: Doesn't work as expected
client.onResetStore(client.writeDefaults);

export default client;
2

There are 2 best solutions below

0
On BEST ANSWER

AFAIK the only way to this is to migrate from Apollo Boost which configures a lot of things under the hood for you and set up Apollo Client manually. After migrating I was able to call onResetStore() as per the docs and everything is working :)

Apollo Boost migration: https://www.apollographql.com/docs/react/advanced/boost-migration.html

0
On

I use Apollo Client 2.x, and Apollo Boost may be the same. I had the same problem with Apollo Client 2.x, and below was the solution for me. In the root file where you configure your Apollo (e.g. App.js):

cache.writeData({data : defaultData });  # I assume you already have this to initialise your default data.

# Then, you just add below underneath.
client.onResetStore(() => {
  cache.writeData({data : defaultData });
});

const App = () => (...