Photo by Alternate Skate on Unsplash
Quickest ways to start using GraphQL APIs in a javascript application
skip the state management setup
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 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:
Conclusion 🎉
And here it is after using the data in the UI
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));