apollo
Create simple implementation of Apollo
client for React
using environment variables
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
import { APP_CONFIG } from '../config';
import { JWT } from '../shared/utils/constants';
// eslint-disable-next-line
const BASE_URL = APP_CONFIG.apiUrl;
const authLink = setContext((_, { headers }) => {
// get the authentication token from local storage if it exists
const token = localStorage.getItem(JWT);
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
});
const httpLink = new HttpLink({
uri: BASE_URL,
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
export default client;