How to add header for apollo client in react native application
createUploadLink
has a headers property which matches to createHttpLink
headers property.
headers: an object representing values to be sent as headers on the request
Sample
const token = await AsyncStorage.getItem('auth.token')
const client = new ApolloClient({
link: createUploadLink({
uri: 'http://localhost:3000/graphql',
headers: {
"Some-Custom-Header": token
}
}),
cache: new InMemoryCache()
})
UPDATE
const getToken = async () => {
const token = await AsyncStorage.getItem('auth.token')
return token
}
const token = getToken()
// 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'
}
})
}
I am using apollo boost, What I did was,
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: 'http://localhost:3000/graphql',
request: async (operation) => {
const token = await AsyncStorage.getItem('token');
operation.setContext({
headers: {
authorization: token
}
});
}
}