Skip to main content

Command Palette

Search for a command to run...

Quickest ways to start using GraphQL APIs in a javascript application

skip the state management setup

Updated
โ€ข2 min read
Quickest ways to start using GraphQL APIs in a javascript application
G

I'm a frontend engineer with 5+ years of experience in building modern web-apps. I like to share my experience through writing, hoping to help other devs learn something interesting or useful.

This is a short walkthrough of querying data from a GraphQL API in a javascript application. It can also be used as a quick reference anytime.

We are using hashnode's graphql API to list down the recent posts by an author.

graphql-request

graphql-request is a very minimal and simple to use GraphQL client.

Compared to GraphQL clients like Apollo or Relay, graphql-request doesn't have a built-in cache and has no integrations for frontend frameworks. The goal is to keep the package and API as minimal as possible.

Let's get started โ˜•

Installation โš™๏ธ

First, let's install the dependencies

npm add graphql-request graphql

Now we can start using graphql-request to fetch data with the request function that it provides.

Query ๐Ÿ“ก

To fetch data using graphql-request, we need an endpoint and a query.

Here I have formed the query using hashnode's graphiql interface

import { gql } from "graphql-request";

const getPosts = gql`
{
  user(username: "gzamann") {
    publication {
      posts {
        brief
        coverImage
        dateAdded
        slug
        title
      }
    }
  }
}
`

It is not required to wrap the query around gql template, but it will help with syntax highlighting and formatting.

Now we can fetch data using this query with the endpoint https://api.hashnode.com/

request(endpoint, query, variables).then((data) => console.log(data))

Client ๐Ÿ“ฎ

We can also declare our graphql client and re-use it across the application so that we don't need to configure the request parameters and the endpoint with every request.

import { GraphQLClient } from "graphql-request";

export const hashnodeClient = new GraphQLClient("https://api.hashnode.com");

Fetching data ๐Ÿ“ฌ

Now let's fetch the data for our react component
I'm setting the posts in a component state so that I can set an initial state and the posts will get rendered once the data is loaded from the server.

const [recentPosts, setRecentPosts] = useState([]);

hashnodeClient.request(getPosts).then((data) => {
  setRecentPosts(data.user.publication.posts.slice(0, 2)); // using first two from the recent posts
});

the result from the above the query looks like this: Screenshot 2022-11-01 at 10.06.46 AM.png

Conclusion ๐ŸŽ‰

And here it is after using the data in the UI Screenshot 2022-11-01 at 10.09.04 AM.png

Using Fetch API ๐Ÿ’ญ

Another quick method to use GraphQL API without installing any additional dependencies is through fetch

fetch('https://api.hashnode.com/', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ query: `
    {
    user(username: "gzamann") {
      publication {
        posts {
          dateAdded
          title
          brief
          slug
          coverImage
        }
      }
    }
  }` 
  }),
})
.then(result => result.json())
.then(result => console.log(result));

https://github.com/prisma-labs/graphql-request
https://api.hashnode.com/