Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass Additional Header when calling mutation in React native apollo client?

How to pass Additional Header when calling mutation in React native apollo client ?

my Client is here:

import { HttpLink } from 'apollo-link-http';
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';

const makeApolloClient = (token) => {
  // create an apollo link instance, a network interface for apollo client
  const link = new HttpLink({
    uri: 'http://x.x.x.x:xxxx/xxxx',
    headers: {
     Authorization: `Bearer ${token}`
    },
  });
  // create an inmemory cache instance for caching graphql data
  const cache = new InMemoryCache();
  // instantiate apollo client with apollo link instance and cache instance
  const client = new ApolloClient({
    link,
    cache
  });
  return client;
};
export default makeApolloClient;

If i need to add additional header to this same client when using query or mutation how can i do it ?

Is it possible with "apollo-link-context" ?

like image 413
Rasheed Avatar asked Sep 24 '19 05:09

Rasheed


People also ask

How do you pass the authorization header in GraphQL playground?

Solution. Before you can successfully call the TimeLine Service from the GraphQL playground you must acquire an authentication token and configure the GraphQL Playground "HTTP HEADERS" tab (bottom of the playground interface) to pass it as a header with your calls to the TimeLine Service.


1 Answers

You haven't specified your React version however assuming you use Hooks you do it as follows. If you aren’t using hooks change the doc version for the links at the bottom of this answer using the drop down in the top left.

Where you have your query:

const GET_USER = gql`
    query getUser{
     node {
       name
       age
     }
   }
`;

You’ll want to run a query with the useQuery hook:

const { loading, error, data } = useQuery(GET_USER, {
    context: {
        headers: {
            "Content-Type": "application/json"
        }
    }
})

Docs:

You can find the docs for each here: - UseQuery: https://www.apollographql.com/docs/react/essentials/queries/ - Context Headers: https://www.apollographql.com/docs/link/links/http/#passing-context-per-query

like image 53
Lachlan Young Avatar answered Sep 28 '22 03:09

Lachlan Young