首页 > 解决方案 > 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;```

标签: graphqlapolloreact-apolloapollo-client

解决方案


我知道我来晚了,但我也遇到了这个问题,发现了这些

您可以在登录突变后调用 clear store

import { useApolloClient } from "@apollo/client";

const client = useApolloClient();

client.clearStore();

推荐阅读