Exploring GraphQL Queries in React

Why GraphQL with React?

GraphQL allows you to request exactly the data you need, reducing over-fetching and under-fetching issues common in REST. React’s component-based architecture pairs beautifully with GraphQL’s declarative data-fetching approach, making it easier to manage state and render UI based on server responses.

Install Apollo Client

npm install @apollo/client graphql

 Configure Apollo Client

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

const client = new ApolloClient({
  uri: 'https://graphqlzero.almansi.me/api',
  cache: new InMemoryCache(),
});

export default client;

Wrap your app with the ApolloProvider in src/main.jsx:

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { ApolloProvider } from '@apollo/client';
import client from './apollo-client';


ReactDOM.createRoot(document.getElementById('root')).render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

Write a GraphQL Query

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


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


function UserList() {
  const { loading, error, data } = useQuery(GET_USERS);


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


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


export default UserList;

Leave a comment

Your email address will not be published. Required fields are marked *