[我正在尝试使用apollo来实现本地状态以及持久化缓存,也许我将这两者混合在一起并且以一种我不应该的方式交织在一起。
我正在尝试实施身份验证。我看到需要一个isAuth应用程序变量,并在apollo中创建了一个状态来保存它。每次登录时,此状态都会改变,注销也会改变。
我遇到一个注销时,我破坏了缓存和localStorage的问题,因此,isAuth本地状态也被擦除了,如果我要刷新这里的页面,它会崩溃,提示isAuth还不存在。
当前,根据文档,我使用cache.writeData ..准备缓存。但是,如果我刷新页面,则localState中的任何内容都会被默认值覆盖,所以我有点介于两者之间
1)刷新并覆盖所有本地状态2)保持本地状态不变,注销后崩溃
而且我无所适从。
https://www.apollographql.com/docs/react/data/local-state/
import ApolloClient, { InMemoryCache } from "apollo-boost";
import { persistCache } from "apollo-cache-persist";
import { ISLOGGEDIN_QUERY } from "./components/gql/Queries"
const cache = new InMemoryCache();
persistCache({
cache,
storage: localStorage
})
const client = new ApolloClient({
uri: "http://localhost:4000/graphql",
cache,
resolvers: {
Mutation: {
changeValue: (_, args, { cache }) => {
const { isAuth } = cache.readQuery({ query: ISLOGGEDIN_QUERY })
cache.writeData({
data: { isAuth: !isAuth }
})
return null;
}
}
},
request: (operation) => {
const token = localStorage.getItem('token');
operation.setContext({
headers: {
authorization: token ? token : ''
}
})
},
});
//set default values
client.cache.writeData({ data: { isAuth: false } })
export default client;
想得太多。我刚刚检查了localStorage的令牌,并设置为默认值]
client.cache.writeData({ data: { isAuth: localStorage.getItem('token') ? true : false } })