Sammy
Sammy

Reputation: 3687

Apollo HttpLink Async

For the following code:

const apolloClient = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: endpoint,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`
    }
  })
});

I need to get endpoint and token asynchronously. How may I do this?

Thank you

Upvotes: 5

Views: 3016

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

You can use apollo-link-context to modify your requests. You can cache the values as shown if you don't fetch them on every request.

let token
let uri
const contextLink = setContext(async () => {
  if (!token) {
    token = await getTokenAsync()
  }
  if (!uri) {
    uri = await getUriAsync()
  }

  return { uri, token }
});

const client = new ApolloClient({
  ...
  link: ApolloLink.from([
    contextLink,
    httpLink,
  ])
})

The above is the preferred way of dynamically setting these parameters. Alternatively, you could just fetch the token and URI before rendering your ApolloProvider and then dynamically create your client instance based on the values.

Upvotes: 6

Related Questions