我需要将Apollo客户端缓存设置为其默认值

时间:2018-09-20 10:29:47

标签: reactjs apollo react-apollo apollo-client apollo-link-state

我有一个使用Apollo Client的React应用程序。我正在使用apollo-link-stateapollo-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;

2 个答案:

答案 0 :(得分:0)

AFAIK唯一的方法是从Apollo Boost迁移,后者为您配置了许多功能并手动设置Apollo Client。迁移后,我可以按照文档调用onResetStore(),一切正常:)

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

答案 1 :(得分:0)

我使用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 = () => (...
相关问题