graphql - Apollo 客户端在页面刷新之前不会向后端发送令牌
问题描述
我一直在开发一个应用程序,当我开始清除缓存时才意识到这个问题,但我的应用程序只能在刷新时正常工作。当我清除所有缓存、刷新然后运行我的应用程序时,我意识到我的查询返回了我的自定义错误“GraphQL 错误:未作为用户身份验证”。
我认为我设置 apollo 客户端的方式有问题。似乎上下文一被实例化就被设置,即使令牌存在,也永远不会改变上下文。它还将解释为什么在登录然后刷新之后,查询会使用令牌,直到本地存储/缓存被清除。所以我的问题是我所拥有的有什么问题?
import { persistCache } from "apollo-cache-persist";
import { ISLOGGEDIN_QUERY } from "./components/gql/Queries"
const cache = new InMemoryCache();
const token = localStorage.getItem('token')
persistCache({
cache,
storage: localStorage
})
const client = new ApolloClient({
uri: "http://localhost:4000/graphql",
cache,
resolvers: {
Mutation: {
changeValue: (_, args, { cache }) => {
const { isAuth } = token ? cache.readQuery({ query: ISLOGGEDIN_QUERY }) : false;
cache.writeData({
data: { isAuth: !isAuth }
})
return null;
}
}
},
request: (operation) => {
operation.setContext({
headers: {
authorization: token ? token : ''
}
})
},
});
//set default values
client.cache.writeData({ data: { isAuth: token ? true : false } })
export default client;```
解决方案
我知道我来晚了,但我也遇到了这个问题,发现了这些
- https://www.apollographql.com/docs/react/networking/authentication/#reset-store-on-logout
- https://stackoverflow.com/a/65204972/13491532
您可以在登录突变后调用 clear store
import { useApolloClient } from "@apollo/client";
const client = useApolloClient();
client.clearStore();
推荐阅读
- reactjs - 承诺没有在 redux thunk 中返回
- python - Scikitlearn - Tensorflow 管道 - 如何在 hd5 / pmml 中保存管道
- dart - Flutter:如何重新运行小部件或构建
- email - Sendgrid 电子邮件 api 显示未经授权的错误
- python - virtualenvwrapper:如何更改 mkvirtualenv 的默认 Python 版本/安装路径
- java - 导航抽屉未正确显示
- java - 需要使用 stringTokenizer 格式化给定字符串“18-MAY-92”并获取月份的 int 值
- r - 如何根据点阵图中的列定义 pch 和颜色
- reactjs - d3 zoom 抛出无法读取 null 错误的属性按钮
- ruby-on-rails - 如何在 Papertrail 的迁移中修改默认列名 whodunnit