首页 > 解决方案 > 我需要将我的 Apollo 客户端缓存设置为默认值

问题描述

我有一个使用 Apollo 客户端的 React 应用程序。我正在使用apollo-link-state并且apollo-cache-persist需要在我的应用程序中调用时将我的商店重置为其默认值client.resetStore()

文档说,在创建客户端时,您应该调用client.onResetStore(stateLink.writeDefaults)它,这将完成这项工作,但writeDefaults由 Apollo Link State 公开,因为我正在使用 Apollo Boost,因此我无法直接访问它。

这是我的 Apollo 客户端代码:

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;

标签: reactjsapolloreact-apolloapollo-clientapollo-link-state

解决方案


我用的是 Apollo Client 2.x,可能和 Apollo Boost 一样。我对 Apollo Client 2.x 也有同样的问题,下面是我的解决方案。在您配置 Apollo 的根文件中(例如 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 = () => (...

推荐阅读