In my React Native application, here's how I set up the Apollo client with an upload link:
My goal is to include a header with a token value that will be sent with every request. However, I've had trouble finding an example specifically for 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()
})
The following code snippet shows how I want to send the token value in the header:
const token = await AsyncStorage.getItem('auth.token')
Update
I'm trying to figure out how to insert the token from AsyncStorage into the header. The use of await
won't work here because it's not within an async function:
const token = await AsyncStorage.getItem('auth.token') // await can't work here
// Initialize 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'
}
})
}