DEV Community

Andrew Lee
Andrew Lee

Posted on

Query GraphQL API with Vanilla Fetch Inside React Component

By using advanced GraphQL clients like Apollo, it's easy to forget that it's like any other HTTP request. Let's make a query to a GraphQL database without using any libraries to gain a deeper appreciation of GraphQL.

Let's interact with a free Countries GraphQL API at the following URL:

https://countries.trevorblades.com/

When we visit the URL in our browser, there is a editor on the website where we can run the following query.

{
  countries {
    code
    name
    emoji
  }
}
Enter fullscreen mode Exit fullscreen mode

Now let's run this query inside of React with vanilla fetch.

import React, { useEffect, useState } from "react";

const Countries = () => {
  const [countries, setCountries] = useState([]);

  useEffect(() => {
    fetch("https://countries.trevorblades.com/", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      },
      body: JSON.stringify({ query: "{ countries { name emoji code } }" })
    })
      .then(res => res.json())
      .then(res => setCountries(res.data.countries));
  });

  return (
    <>
      <h1>Countries</h1>
      <div>
        {countries.map(country => {
          const { code, name, emoji } = country;
          return (
            <div key={code}>
              {emoji} {name}
            </div>
          );
        })}
      </div>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

As we can see here, a GraphQL query is simply a POST request with the query inside of the body.

Top comments (1)

Collapse
 
dance2die profile image
Sung M. Kim

With all those graphql wrapper libraries, it felt like a magic.

This post made it look more familiar :)