[英]Check for existing instance of ApolloClient to clear cache?
We have a React/GraphQL app inside of a main "app".我们在主“应用程序”中有一个 React/GraphQL 应用程序。 When the user logs out we want to clear the GQL cache.
当用户注销时,我们要清除 GQL 缓存。 However, the logout functionality exists in the wrapper app, not the React app.
但是,注销功能存在于包装应用程序中,而不是 React 应用程序中。
When we log back in the cache is not cleared, which needs to be solved.当我们重新登录时缓存没有被清除,这是需要解决的。 A couple of questions on how to solve this:
关于如何解决这个问题的几个问题:
1) can we check for a cache when the React app tries to create a new instance? 1) 当 React 应用尝试创建新实例时,我们可以检查缓存吗? Is there a "version" flag we can add?
我们可以添加一个“版本”标志吗?
const client = new ApolloClient({
link: authLink.concat(restLink),
cache: () => {
if (client.cache) {
client.cache.reset()
}
return new InMemoryCache();
}
});
2) or can we find the existing client App through any other window or global object? 2)或者我们可以通过任何其他window或全局object找到现有的客户端App吗? 3) should the react app set the client as part of local state and then compare client with
useRef
perhaps? 3)反应应用程序是否应该将客户端设置为本地 state 的一部分,然后将客户端与
useRef
进行比较? If they don't match, then reset?如果他们不匹配,然后重置?
Open to suggestions...接受建议...
The official way to clear the cache is calling resetStore
in the client instance.清除缓存的官方方法是在客户端实例中调用
resetStore
。 You can get the client instance inside of any component within the Apollo context by using eg the useApolloClient
hook您可以使用例如
useApolloClient
钩子在 Apollo 上下文中的任何组件内获取客户端实例
function MyLogoutButton() {
const client = useApolloClient();
const onLogout = () => {
backend.logout();
client.resetStore();
};
return <button onClick={onLogout}>Logout</button>;
}
Maybe this is doing what you want to do.也许这正在做你想做的事。 You seem to be trying to create a new instance of the client, but this is not needed.
您似乎正在尝试创建客户端的新实例,但这不是必需的。 The
resetStore
method was build for exactly this use case. resetStore
方法正是为这个用例而构建的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.