I am online
← Back to Articles

Simple GraphQL Example in React

GraphQLJune 20, 2024

Introduction

GraphQL is a powerful query language for APIs that allows clients to request exactly the data they need. Integrating GraphQL with React can help create efficient, flexible, and scalable applications.

  • Installation
npx create-react-app my-graphql-app
cd my-graphql-app
npm install @apollo/client graphql
  • Creating an Apollo Client
// src/apolloClient.js
import { ApolloClient, InMemoryCache } from "@apollo/client";

const client = new ApolloClient({
  uri: "https://your-graphql-endpoint.com/graphql",
  cache: new InMemoryCache(),
});

export default client;
  • Providing the Apollo Client
// src/index.js
import React from "react";
import ReactDOM from "react-dom";
import { ApolloProvider } from "@apollo/client";
import client from "./apolloClient";
import App from "./App";

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById("root")
);
  • Making a Query
// src/App.js
import React from "react";
import { useQuery, gql } from "@apollo/client";

const GET_USERS = gql`
  query GetUsers {
    users {
      id
      name
      email
    }
  }
`;

const App = () => {
  const { loading, error, data } = useQuery(GET_USERS);

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

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {data.users.map((user) => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;

Happy coding!