Convert traditional GraphQL Query to?Hooks

Convert traditional GraphQL Query to?Hooks

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.

要查看或添加评论,请登录

Muhammad Anser的更多文章

  • How to make an offline first React App

    How to make an offline first React App

    I did a POC on offline first React app and decided to share my POC with the developer community. Suppose we are to…

    7 条评论
  • Convert Redux to Hooks

    Convert Redux to Hooks

    In this article, I will try to explain how you can use Redux with React Hooks. React Redux gave support for Hooks in…

    7 条评论
  • Why I turned down job offers from some big companies

    Why I turned down job offers from some big companies

    When there are more job seekers looking for work than jobs available (think: the Great Recession) it’s rare for…

    2 条评论
  • Using React Hooks with the GraphQL API

    Using React Hooks with the GraphQL API

    What are Hooks actually? Hooks are the functions that lets you get to 'state' without using a class component. Rather…

    1 条评论
  • ReactJS or AngularJS, which to choose

    ReactJS or AngularJS, which to choose

    In the previous couple of years, sites have developed into complex web applications, and what used to be place that is…

  • 5 quick JavaScript hacks

    5 quick JavaScript hacks

    1. Bool condition check This is one of the basic oversights that each software engineer would have done at least once…

  • Things I learned so far as a Software Engineer

    Things I learned so far as a Software Engineer

    I'd love to share five of the most imperative things I've adapted up to this point; I believe that all developers…

  • You can’t hide from Facebook

    You can’t hide from Facebook

    Facebook has since quite a while ago enabled you to download a chronicle of the considerable number of information the…

  • Front-end vs Back-end. Which and Why?

    Front-end vs Back-end. Which and Why?

    I have been working as a developer for more than 5 years now, having almost 3 years experience in backend development…

  • Being toxic in workplace

    Being toxic in workplace

    I have been working as a software engineer for more than 5 years now. I have worked in typical software industry as…

    4 条评论

社区洞察

其他会员也浏览了