reactjs - 我需要将我的 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;
解决方案
我用的是 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 = () => (...
推荐阅读
- android - 无法解决:firebase-common
- facebook - Facebook Graph API:获取到用户时间线的链接不起作用
- google-chrome-extension - 如何使用 AngularJS 在此页面中设置日期
- javascript - HTML5 前后比较滑块
- c - 在 C 中编写 bmp 文件会产生错误的结果
- javascript - WKWebView - JavaScript 警报功能在 Objective-C 中不起作用
- android - Unity GooglePlayGamesPlugin 包导入问题
- meteor - Meteor Tracker.autorun 行为
- c++ - 类型名的概念/SFINAE 错误
- react-native - 所有选项卡的 react-native-navigation (wix) v2 静态场景