【发布时间】:2020-02-26 02:41:35
【问题描述】:
我一直在开发一个应用程序,直到我开始清除缓存时才意识到这个问题,但我的应用程序只有在刷新时才能正常工作。当我清除所有缓存、刷新然后运行我的应用程序时,我意识到我的查询返回了我的自定义错误“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;```
【问题讨论】:
标签: graphql apollo react-apollo apollo-client