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 {
  ApolloProvider as Provider,
} from '@apollo/client'
import React, { useEffect } from 'react'
import { StateProviderProps } from './../../types'
import { useAuthTokenState } from './../authToken/AuthTokenState'

const client = new ApolloClient({
  uri: '',
  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.


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