调用client.clearStore()之后如何为ApolloClient实例的标头

时间:2019-12-18 04:48:13

标签: apollo react-apollo react-apollo-hooks

我目前正在使用用户注销功能,但是遇到client.clearStore

问题

Apollo客户端使用标头index.ts中的令牌初始化:

import ApolloClient from 'apollo-boost'

const client = new ApolloClient({
  cache,
  request: async operation => {
    const token = localStorage.getItem('token')
    if (token) operation.setContext({ headers: { token } })
  },
})

export default client

logout.ts中,我从本地存储中删除令牌并清除该存储:

import { ApolloClient } from 'apollo-boost'

const logout = (
  client: ApolloClient<object>
) => (): true => {
  localStorage.removeItem('token')
  client.clearStore()
}

将令牌添加到本地存储,并在登录成功(login.ts)后更新存储数据:

const onLoginSuccess = () => {
  localStorage.setItem(localStorageKey, JSON.stringify(newValue))
  // client is initialised in higher function by const client = useApolloClient()
  client.writeData({ data: { token: newValue } })
}

因此,一旦调用client.writeData({ data: { token: newValue } }),由于存储更新,const client = new ApolloClient({ ... })应该会自动触发,但在我的情况下不会触发,这导致无法在标头中设置令牌的问题重新登录后,除非刷新页面。

我想知道在运行client.clearStore()之后再运行client.writeData()后,如何使const client = new ApolloClient({})能够被自动触发?

0 个答案:

没有答案