Apollo Client in 6 minutes with ReactJS

Valmy Machado - Sep 10 - - Dev Community

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

Setup new project

First of all, create a new project. I'm going to use the Vite, but feel free to use another tool.

run npm create vite@latest and configure your project.

Install Dependencies

Install these two dependencies

npm install @apollo/client graphql

Initialize Apollo Cliente

Go to the main.jsx file, and initialize the Apollo Client. Here, we define a new instance, with the uri (the url of your GraphQL server), and cache (Apollo Client uses to cache results after fetching them).

import {
  ApolloClient,
  InMemoryCache,
  ApolloProvider,
} from "@apollo/client";

const client = new ApolloClient({
  uri: "https://countries.trevorblades.com/",
  cache: new InMemoryCache(),
});

createRoot(document.getElementById('root')).render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
)
Enter fullscreen mode Exit fullscreen mode

As you can see, we use the ApolloProvider encapsulating the App and passing the client via props, so we can utilize Apollo Client in any component we want.

Fetch data with useQuery

Go to the App.jsx file, and import the useQuery and gql from @apollo/client.

GraphQL Query: The GET_COUNTRIES query requests the code, name, and capital fields for all countries.

useQuery Hook: The Apollo Client’s useQuery hook is used to execute the query and retrieve the following states:

  • loading: Displays a "Loading..." message while the data is being fetched.

  • error: Shows an error message if the request fails.

  • data: Once the data is returned, it maps over the list of countries.

Rendering: For each country, a <div> is created, displaying the country’s name and capital. The code is used as a unique key for each item, ensuring proper performance when rendering lists.

import { useQuery, gql } from '@apollo/client';

const GET_COUNTRIES = gql`
  query {
    countries {
      name
      capital
    }
  }
`;

export default function App() {
  const { loading, error, data } = useQuery(GET_COUNTRIES);

  if(loading) return <p>Loading...</p>
  if(error) return <p>Error: {error.message}</p>

  return data.countries.map(({ code, name, capital }) => (
    <div key={code} style={{ borderBottom: '1px solid white', marginBottom: '5px' }}>
      <p>Name: {name}</p>
      <p>Capital: {capital}</p>
    </div>
  ))
}

Enter fullscreen mode Exit fullscreen mode

In just 6 minutes, you’ve learned how to integrate Apollo Client with a ReactJS application to connect to a GraphQL server and efficiently list data. This approach provides a powerful way to consume GraphQL APIs, simplifying state management and data handling in frontend applications.

While this tutorial focused only on queries, Apollo Client also supports more complex operations like mutations and subscriptions, which we can explore in future posts. With this foundation, you’re ready to start building dynamic, data-driven interfaces using GraphQL and ReactJS.

.
Terabox Video Player