Managing states in React apps with Apollo Client: overview

Graphql is The most popular technology to build jampstack/SPAs apps, it's enabling you to select only the information or operations you need depending on your use case, we cover in this article how to start configure Apollo Client as Graphql agent in React apps.

Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. Use it to fetch, cache, and modify application data, all while automatically updating your UI.

Apollo Client is designed for a modern React application because it provides hooks out of the box that helps us to execute queries and make mutations, also he supports a lot of libraries & frameworks such as Vue, Solid.js, Svelte, etc.

Also with some pieces of code, we can cache queries and combine, validate and sync them with remote data.

Setup Apollo Client:

Install dependencies:

yarn add @apollo/client graphql

Apollo Client by default support TypScript 😍, no need for additional types.

Setup Apollo Client:

First of all we need to initialize ApolloClient instance that has a constructor accept two parameters uri and cache

  • uri is URL of Graphql server.
  • cache is instance of InMemoryCache, that used to cache results of queries locally.

We can pass more than those parameters like link, it's powerful when we need to add headers before sending every HTTP request, we can do a lot of things like: user is logged out of the application if the server returns a 401 code, add connection with WebSocket to keep us sync with real data. we will cover this topic in next articles.

NOTE: One of uri or link is required. If you provide both, link takes precedence.

Example:

import {
  ApolloClient,
  ApolloProvider,
  createHttpLink,
  from,
  InMemoryCache,
} from '@apollo/client'
import { setContext } from '@apollo/client/link/context'
import { onError } from '@apollo/client/link/error'

const errorLink = onError(
  ({ graphQLErrors, networkError, forward, operation }) => {
    if (graphQLErrors) {
      graphQLErrors.map(({ message, extensions, locations, path }) =>
        console.log(
          `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}, Extension: ${extensions.code}`
        )
      )
    }

    if (networkError) {
      console.log(`[Network error]: ${networkError}`)
    }
    forward(operation)
  }
)

const withToken = setContext(async (_, { headers }) => {
  const token = 'token value here'
  return {
    headers: {
      ...headers,
      ...(token && { Authorization: `Bearer ${token}` }),
    },
  }
})

const httpLink = createHttpLink({
  uri: process.env.REACT_APP_BACKEND_URI,
})

const client = new ApolloClient({
  link: from([errorLink, withToken, httpLink]),
  cache: new InMemoryCache(),
})

onError: when a request fails the workflow inside this function executed. setContext: with this function we can set context of the request before send it to graphql server.

Link is mechanism helps us to customize the flow of data between Apollo Client and your GraphQL server. You can define your client's network behavior as a chain of link objects.

For InMemoryCache's constructor, we can pass some params to change the behavior of caching

conclusion:

We cover in this article how to start using Apollo Client in react app with zero config cache that help us out of the box to caching the results of queries executed, we are ready to make some queries and get information from graphql server. Read how to execute the queries.

More details about link : https://www.apollographql.com/docs/react/api/link/introduction