Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override Apollo Client headers from individual queries in my components?

Tags:

When I initialize my Apollo client, I make an Apollo Link with the header hello: "world". Is there a way to override the hello header value from a component using hooks? I thought this would work but it still uses the Client header:

useQuery(<QUERY>,{
    context:{
        headers:{
            hello: "Canada"
        }
    }
})

like image 386
Aej11a Avatar asked Sep 11 '19 19:09

Aej11a


2 Answers

Your code seems correct. After doing some testing it appears that it is not possible to overwrite existing headers.

  const { data, loading, error } = useQuery(ALL_GAMES, {
    context: { headers: { authentication: 'some value', test: 'some value' } }
  });

Perhaps if you pass in a whole new client to useQuery - you could create the client using a factory function

like image 115
Jonathan Irwin Avatar answered Sep 30 '22 07:09

Jonathan Irwin


I ran into the same issue when trying to override the authorization header of a request. I solved it by spreading operation.getContext().headers when I'm setting the headers in my link. Code:

const authLink = new ApolloLink((operation, forward) => {
    operation.setContext({
      headers: {
        authorization: authToken,
        ...operation.getContext().headers,
      },
    });

    return forward(operation);
  });

Then the code you included should work as expected.

like image 44
austin Avatar answered Sep 30 '22 07:09

austin