我想实现apollo-link-context / react-native / graphql,但是Apollo setContext不保存accessToken。如果我用console.log检查它,我将无法定义。它看起来像setContext调用之前,然后我从服务器获取令牌。因此setContext无法及时保存令牌。有人可以帮我吗
App.js
import React from 'react'
import { ApolloProvider } from 'react-apollo'
import { ApolloProvider as ApolloHooksProvider } from 'react-apollo-hooks'
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import { InMemoryCache } from 'apollo-cache-inmemory'
import * as Keychain from 'react-native-keychain'
import AppNavigator from './AppNavigator'
const httpLink = createHttpLink({
uri: 'http://localhost:4000'
})
const authLink = setContext(async (_, { headers }) => {
const tokens = await Keychain.getGenericPassword()
const accessToken = tokens.accessToken
console.log('accessTokenSetContext', accessToken)
return {
headers: {
...headers,
authorization: accessToken ? `Bearer ${accessToken}` : ''
}
}
})
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
connectToDevTools: true
})
const App = () => {
return (
<ApolloProvider client={client}>
<ApolloHooksProvider client={client}>
<AppNavigator />
</ApolloHooksProvider>
</ApolloProvider>
)
}
export default App