Data Fetching with GraphQL

Last Updated : 12 Mar, 2026

GraphQL is an open-source query language for APIs that allows clients to request only the specific data they need from the server. Unlike traditional REST APIs that return entire resources, GraphQL enables precise and flexible data retrieval.

  • Clients can specify exactly which fields they want in a query.
  • Reduces unnecessary data transfer and improves network efficiency.
  • Returns structured responses that match the requested query format.

Fetching GraphQL Data with React

React applications commonly use Apollo Client to fetch and manage GraphQL data efficiently.

Step 1: Create a React Application

Create a new React project using the following command.

npx create-react-app graphql

Step 2: Move to the Project Folder

Navigate to the created project directory.

cd graphql

Project Structure:

react-str

Step 3: Configure Apollo Client in App.js

Apollo Client connects the React application to a GraphQL API and manages queries along with caching of data.

Create Apollo Client:

Node
const { ApolloClient, InMemoryCache } = require('@apollo/client');

const client = new ApolloClient({
  uri: 'https://graphql-pokeapi.graphcdn.app/',
  cache: new InMemoryCache(),
});

Wrap the Application with ApolloProvider:

ApolloProvider wraps the main App component and provides access to the GraphQL client across all components in the application.

Node
function ApolloApp() {
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}

Step 4: Define a GraphQL Query

The following query retrieves a list of Pokémon with selected fields.

Node
import { gql } from '@apollo/client';

const GET_POKEMONS = gql`
  query getPokemons {
    pokemons(limit: 10, offset: 0) {
      count
      next
      previous
      status
      message
      results {
        id
        name
        image
      }
    }
  }
`;

Step 5: Fetch Data Using useQuery

Apollo provides the useQuery hook to execute queries and handle loading and error states.

Node
import { useQuery } from '@apollo/client';

function App() {
  const { loading, error, data } = useQuery(GET_POKEMONS);

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

  return (
    <div>
      <h1>Pokemons</h1>
      <ul>
        {data?.pokemons?.results?.map(pokemon => (
          <li key={pokemon.id}>
            {pokemon.name}
          </li>
        ))}
      </ul>
    </div>
  );
}

Complete App.js Code

Node
import React from 'react';
import { ApolloProvider, useQuery, gql } from '@apollo/client';
import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://graphql-pokeapi.graphcdn.app/',
  cache: new InMemoryCache(),
});

const GET_POKEMONS = gql`
  query getPokemons {
    pokemons(limit: 10, offset: 0) {
      count
      next
      previous
      status
      message
      results {
        id
        name
        image
      }
    }
  }
`;

function App() {
  const { loading, error, data } = useQuery(GET_POKEMONS);

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

  return (
    <div>
      <h1>Pokemons</h1>
      <ul>
        {data?.pokemons?.results?.map(pokemon => (
          <li key={pokemon.id}>
            {pokemon.name}
          </li>
        ))}
      </ul>
    </div>
  );
}

function ApolloApp() {
  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}

export default ApolloApp;

Output:

file

Fetching GraphQL Data Using Fetch API

The Fetch API can be used to send GraphQL queries directly to a GraphQL endpoint using HTTP requests. It allows developers to retrieve data from a GraphQL server without using additional client libraries.

Step 1: Create the GraphQL Query

Define the GraphQL endpoint and write the query to request the required data.

Node
const graphqlEndpoint = 'https://graphql-pokeapi.graphcdn.app/';

const graphqlQuery = `
  query getPokemons {
    pokemons(limit: 10, offset: 0) {
      count
      next
      previous
      status
      message
      results {
        id
        name
        image
      }
    }
  }
`;

Step 2: Configure Fetch Options

Set the HTTP request method and include the GraphQL query in the request body.

Node
const fetchOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query: graphqlQuery }),
};

Step 3: Send the Request

Use the Fetch API to send the query to the GraphQL server and process the response.

Node
fetch(graphqlEndpoint, fetchOptions)
  .then(response => response.json())
  .then(data => {
    console.log('GraphQL Data:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Complete fetchGraphQL.js Code

Node
const graphqlEndpoint = 'https://graphql-pokeapi.graphcdn.app/';

const graphqlQuery = `
  query getPokemons {
    pokemons(limit: 10, offset: 0) {
      count
      next
      previous
      status
      message
      results {
        id
        name
        image
      }
    }
  }
`;

const fetchOptions = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ query: graphqlQuery }),
};

fetch(graphqlEndpoint, fetchOptions)
  .then(response => response.json())
  .then(data => {
    console.log('GraphQL Data:', data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

Output:

data

Fetching Data with GraphiQL

GraphiQL is an interactive in-browser IDE used to explore and test GraphQL APIs. It allows developers to write queries, execute them, and view responses with helpful features like auto-completion and syntax highlighting.

Step 1: Create a Basic GraphQL Server

Create a simple Node.js server that exposes a GraphQL endpoint and enables the GraphiQL interface.

Filename: server.js

Node
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

const root = {
  hello: () => {
    return 'Hello, GFG!';
  },
};

const app = express();

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

const PORT = process.env.PORT || 4000;

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}/graphql`);
});

Step 2: Start the Server

Run the following command in the terminal to start the Node.js server.

node server.js

Output:

Server running on http://localhost:4000/graphql

Step 3: Test the Query in GraphiQL

Open the GraphiQL interface in the browser and run the following query.

query {
hello
}

Output:

file

Comment