apollo-client - can I adjust apolloLinks dynamically after apollo-client instantiation?

1.4k Views Asked by At

How can I update the token during runtime in an instantiated apollo-client instance?

const middleware = new ApolloLink((operation, forward) => {
    operation.setContext({
        headers: new HttpHeaders().set('Authorization', 'Bearer ' + token || null)});
        return forward(operation);
    });


apollo.createNamed(id, {
    link: from([logoutLink, middleware, http]),
    cache: new InMemoryCache(),
});

The apollo instance has a link property, which itself is a ApolloLink instance, which has the concat method.

apollo.getclient().link.concat()

But calling that concat returns a new ApolloLink instance. Is there a way to update the client instance with this new ApolloLink?

1

There are 1 best solutions below

1
On BEST ANSWER

You don't need to create a new ApolloLink -- you pass a function to ApolloLink's constructor that's ran each time a request is made, so just handle that logic inside the function:

const middleware = new ApolloLink((operation, forward) => {
  const headers = new HttpHeaders()
  const token = getTokenFromWherever()
  headers.set('Authorization', 'Bearer ' + token)
  operation.setContext({ header })
})