Creating a new apollo client that depends on a value from a global state in React

I am working on a react project and want to set up an apollo client and pass access token to headers but my access token is in my global state. I tried creating the client within the component but ended up with an infinite loop.

import {
  ApolloClient,
  ApolloProvider as Provider,
  InMemoryCache,
} from '@apollo/client'
import React, { useEffect } from 'react'
import { StateProviderProps } from './../../types'
import { useAuthTokenState } from './../authToken/AuthTokenState'

const client = new ApolloClient({
  uri: 'https://subdomain.domain.com/graphql',
  cache: new InMemoryCache(),
  // headers: {
  //   Authorization: 'Bearer' + state?.accessToken,
  // },
})

const ApolloProvider = ({ children }: StateProviderProps) => {
  const { state } = useAuthTokenState()

  return <Provider client={client}>{children}</Provider>
}

export default ApolloProvider

i am looking for any idea that could help make this work.

thanks

You’re going to have to create your own link and pass that to ApolloClient. Then you can have a function that pulls from a local storage point and you can use whatever logic.

1 Like