【发布时间】:2018-10-14 04:19:31
【问题描述】:
这就是我在我的 react native 应用程序中使用上传链接定义 apollo 客户端的方式。
我想添加一些带有令牌值的标头,它会随每个请求一起发送。但不幸的是,我没有找到 react native 的示例。
import { AsyncStorage } from 'react-native'
import { ApolloClient } from 'apollo-client'
import { createUploadLink } from 'apollo-upload-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
const client = new ApolloClient({
link: createUploadLink({
uri: 'http://localhost:3000/graphql'
}),
cache: new InMemoryCache()
})
我想在标题中发送这个值:
const token = await AsyncStorage.getItem('auth.token')
更新
我不知道如何将令牌从 AsyncStorage 插入到标头。 Await 不能在这里工作,因为它没有在异步函数中使用:
const token = await AsyncStorage.getItem('auth.token') // await can't work here
// Initiate apollo client
const client = new ApolloClient({
link: createUploadLink({
uri: 'http://localhost:3000/graphql',
headers: {
authorization: token
}
}),
cache: new InMemoryCache()
})
// Wrap apollo provider
const withProvider = (Component, client) => {
return class extends React.Component {
render () {
return (
<ApolloProvider client={client}>
<Component {...this.props} client={client} />
</ApolloProvider>
)
}
}
}
export default async () => {
Navigation.registerComponent('MainScreen', () => withProvider(MainScreen, client))
Navigation.startSingleScreenApp({
screen: {
screen: 'MainScreen'
}
})
}
【问题讨论】:
标签: javascript react-native apollo-client