Convert traditional GraphQL Query to?Hooks
Muhammad Anser
Software Craftsman ?? | Teacher ???? | Speaker ?? | Writer ??? | Hands-on Developer ??????
If you don’t know about React hooks and how to use them with the GraphQL API, have a look at this article first.
https://www.dhirubhai.net/pulse/using-react-hooks-graphql-api-muhammad-anser/
In this article I will tell you how you can easily convert your GraphQL queries to React hooks.
GraphQL Query:
At its simplest, GraphQL is about asking for specific fields on objects. Let’s start by looking at a very simple query.
{ hero { name } }
The result we get when we run it.
{ "data": { "hero": { "name": "Tom Latham" } } }
You can see that the query has exactly the same shape as the result. This is essential to GraphQL, because you always get back what you expect, and the server knows exactly what fields the client is asking for.
Let’s look at a real time example for making a GraphQL query inside a React class component.
npm install react-apollo
This package exports the Query for us.
npm install graphql-tag
A JavaScript template literal tag that parses GraphQL query strings into the standard GraphQL AST.
Then import the Query from the installed package and use it as shown in the example below.
import { Query } from 'react-apollo'; import gql from 'graphql-tag'; return ( <Query query={PROJECT} variables={{ projectId: 1 }}> {({ loading, error, data }) => ( {!loading && <span> {data.Project.name} </span> } )} </Query> ) const PROJECT = gql` query($projectId: Int!) { Project(id: $projectId) { name } } `;
If you notice that we also two more states ‘error’ and ‘loading’ other than the actual data.
Loading State
When this component mounts, the GraphQL query sent in the background may not have been completed. But we need to handle that temporary state of no data and hence we return some useful text during loading state. In this loading state, typically you can do fancy things like displaying a loading spinner.
Error State
Now, the query could also end up in an error state due to various reasons. Sometimes the graphql query could be wrong, or the server isn't responding. Whatever may be the reason, the user facing UI should show something to convey that an error has occurred. In this error state, typically you can send these error messages to third-party services to track what went wrong.
Now if you are to change the traditional query to hooks, you have to do the following:
npm install @apollo/react-hooks
It will provide us with the ‘useQuery’ hook, import this hook and use it as shown in below example for your functional React component.
import { useQuery } from '@apollo/react-hooks'; import gql from 'graphql-tag'; const { data, loading, error } = useQuery(PROJECT, { variables: { projectId: 1 } }); if (loading) return <p>Loading...</p>; // if data is still loading if (error) return `Error! ${error.message}`; // if there is any error return ( <span> {data.Project.name} </span> ) const PROJECT = gql` query($projectId: Int!) { Project(id: $projectId) { name } } `;
So both the examples above are making a GraphQL query to Project model to fetch ‘name’ of a specific project after we pass an ID as variable.
First example is demonstration of a traditional query for React class component while second example is for React functional component using hooks.
Conclusion:
Hooks are a powerful addition to React, also ‘react-hooks’ is a powerful library to use hooks with GraphQL in your React app. I would recommend get your hands dirty with graphql queries using hooks now as you already have the foundation.
You learnt something new today? Comments and feedback always make the writer happy ;)
About the Author:
Having 7+ years of professional software development experience in various cutting edge technologies, currently working as a Principal Software Engineer in a silicon valley based company in full stack capacity using ReactJs and Apollo-GraphQL. I love to write about technology and share my professional experience with everyone.