Apollo React Client Configuration

Dilip Kumar
2 min readAug 8, 2018

Following are few different way to configure React Client.

Using apollo-boost module

Apollo team wrapped most widely used Apollo react client configuration in apollo-boost module for easy to use. Following is example.

npm install apollo-boost react-apollo graphql --save

Apollo Boost includes some packages that we think are essential to developing with Apollo Client. Here’s what’s included:

  • apollo-client: Where all the magic happens
  • apollo-cache-inmemory: Our recommended cache
  • apollo-link-http: An Apollo Link for remote data fetching
  • apollo-link-error: An Apollo Link for error handling
  • apollo-link-state: An Apollo Link for local state management
import ApolloClient from "apollo-boost";const client = new ApolloClient({
uri: "https://w5xlvm3vzz.lp.gql.zone/graphql"
});

ApolloClient can be either used with React or even with pure Javascript code to fetch data from GraphQL.

import gql from "graphql-tag";client
.query({
query: gql`
{
rates(currency: "USD") {
currency
}
}
`
})
.then(result => console.log(result));

To connect ApolloClient to React, we need ApolloProvider component from react-apollo . It acts as a context provider. It wraps React component and place client on the context.

import React from "react";
import { render } from "react-dom";
import ApolloClient from "apollo-boost";
import { ApolloProvider } from "react-apollo";
const client = new ApolloClient({
uri: "https://w5xlvm3vzz.lp.gql.zone/graphql"
});
const App = () => (
<ApolloProvider client={client}>
<div>
<h2>My first Apollo app 🚀</h2>
</div>
</ApolloProvider>
);
render(<App />, document.getElementById("root"));

Use individual module

To create a basic client with the same defaults as Apollo Boost, first we need to install some packages:

npm install apollo-client apollo-cache-inmemory apollo-link-http apollo-link-error apollo-link --save

To complete the process, we will need to manually attach our cache and link to the client:

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

const client = new ApolloClient({
link: ApolloLink.from([
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.log(`[Network error]: ${networkError}`);
}),
new HttpLink({
uri: 'https://w5xlvm3vzz.lp.gql.zone/graphql',
credentials: 'same-origin'
})
]),
cache: new InMemoryCache()
});

--

--