Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add header for apollo client in react native application

This is how I define the apollo client with an upload link in my react native application.

I would like to add some header with a token value, which gets send with every request. But unfortunately I did not find an example 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()
})

I would like to send this value in the header:

const token = await AsyncStorage.getItem('auth.token')

Update

I don't know how to insert the token from a AsyncStorage to the header. Await can't work here as it is not used in an async function:

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'
    }
  })
}
like image 726
user3142695 Avatar asked May 03 '18 18:05

user3142695


Video Answer


3 Answers

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'
    }
  })
}
like image 171
bennygenel Avatar answered Sep 28 '22 08:09

bennygenel


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
      }
    });
  }
}
like image 42
Haseeb A Avatar answered Sep 28 '22 07:09

Haseeb A


Using callback on getItem also works

import { ApolloClient, HttpLink, ApolloLink, InMemoryCache } from 'apollo-boost'

const httpLink = new HttpLink({
  uri: 'http://localhost:4000/graphql',
})

const authLink = new ApolloLink((operation, forward) => {
  AsyncStorage.getItem('AuthToken').then(token => {
    operation.setContext({
      headers: {
        authorization: token ? `Bearer ${token}` : '',
      },
    })
  })
  return forward(operation)
})

const apolloClient = new ApolloClient({
  cache: new InMemoryCache(),
  link: authLink.concat(httpLink),
})
like image 27
Andy Avatar answered Sep 28 '22 09:09

Andy