最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add header for apollo client in react native application - Stack Overflow

programmeradmin2浏览0评论

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'
    }
  })
}

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'
    }
  })
}
Share Improve this question edited May 3, 2018 at 21:39 user3142695 asked May 3, 2018 at 18:50 user3142695user3142695 17.3k55 gold badges194 silver badges374 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 9

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
      }
    });
  }
}

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),
})

As for Jun 2021, I created a gist file solution that applies in both AsyncStorage and React-Redux. If you don't want to install any other dependencies e.g apollo-boost given that you are using apollo-client this is for you. I hope it works with you too.

P.S

This implementation is for setting up token or authentication headers on your apoll-client graphql request

发布评论

评论列表(0)

  1. 暂无评论