Reader small image

You're reading from  Learn React with TypeScript - Second Edition

Product typeBook
Published inMar 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781804614204
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Carl Rippon
Carl Rippon
author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon

Right arrow

Interacting with GraphQL APIs

GraphQL APIs are web APIs that have a special language for interacting with them. These APIs are a very popular alternative to REST APIs with React frontends.

In this chapter, we’ll first understand the special GraphQL language, executing some basic queries on the GitHub GraphQL API. We will then build a React app that allows users to search for a GitHub repository and star it, experiencing the benefits of GraphQL over REST.

The app will use the browser’s fetch function with React Query to interact with the GitHub GraphQL API. We will then refactor the implementation of the app to use a specialized GraphQL client called Apollo Client.

We’ll cover the following topics:

  • Understanding the GraphQL syntax
  • Getting set up
  • Using the React Query with fetch
  • Using Apollo Client

Technical requirements

We will use the following technologies in this chapter:

All the code snippets in this chapter can be found online at https://github.com/PacktPublishing/Learn-React-with-TypeScript-2nd-Edition/tree/main/Chapter10.

Understanding the GraphQL syntax

Like React Query, GraphQL refers to a request to fetch data as a query. In the following subsections, we’ll learn how to write a basic GraphQL query that returns data from a couple of fields. These fields will have primitive values and so the result will be flat. We’ll then learn how to write a more advanced query containing object-based field values that have their own properties. Lastly, we will learn how to make queries more reusable using parameters.

Returning flat data

Carry out the following steps to use the GitHub GraphQL API Explorer to get information about your GitHub user account:

  1. Open the following URL in a browser to open the GitHub GraphQL API Explorer: https://docs.github.com/en/graphql/overview/explorer.
  2. Sign in using the Sign in with GitHub button if you aren’t signed in already. A GraphQL API Explorer page appears, as follows:
...

Setting up the project

In this section, we will start by creating the project for the app we will build. We will build a React app that allows users to search for a GitHub repository and star it. It will use the GitHub GraphQL API, so we will generate a personal access token (PAT) for this and store it in an environment variable.

Creating the project

We will develop the app using Visual Studio Code and a new Create React App-based project setup. We’ve previously covered this several times, so we will not cover the steps in this chapter – instead, see Chapter 3, Setting Up React and TypeScript.

We will style the app with Tailwind CSS. We have previously covered how to install and configure Tailwind in a Create React App in Chapter 5, Approaches to Styling Frontends. So, after you have created the React and TypeScript project, install and configure Tailwind.

We will use React Hook Form to implement the form that creates blog posts, and the @tailwindcss/forms...

Using React Query with fetch

In this section, we will build an app containing a form that allows users to search and star GitHub repositories. The app will also have a header containing our name from GitHub. We will use the browser fetch function with React Query to interact with the GitHub GraphQL API. Let’s get started.

Creating the header

We will create the header for the app, which will contain our GitHub name. We will create a Header component containing this, which will be referenced from the App component. The Header component will use React Query to execute a function that gets our GitHub name calling the GitHub GraphQL API.

Creating a function to get viewer information

Carry out the following steps to create a function that makes a request to the GitHub GraphQL API to get details about the logged-in viewer:

  1. We will start by creating a folder for the API calls. Create an api folder in the src folder.
  2. Now, we will create a type that the function...

Using Apollo Client

In this section, we will learn about Apollo Client and use it within the app we have built, replacing the use of React Query and fetch.

Understanding Apollo Client

Apollo Client is a client library for interacting with GraphQL servers. It has query and mutation hooks called useQuery and useMutation, like React Query. Apollo Client also stores the data in a client cache like React Query and requires a provider component placed above the components requiring GraphQL data.

One thing that Apollo Client does that React Query doesn’t is that it interacts with the GraphQL API directly instead of requiring a function to do this.

Installing Apollo Client

Our first job is to install Apollo Client, which we can do by running the following command in a terminal:

npm i @apollo/client graphql

This library includes TypeScript types, so no additional package is required to be installed.

Refactoring the App component

The first component...

Summary

In this chapter, we started by learning the GraphQL syntax for queries and mutations. A great feature of GraphQL is the ability to request and receive only the required objects and fields. This can really help the performance of our apps.

We used React Query and fetch to interact with a GraphQL API. This is very similar to interacting with a REST API, but the HTTP method needs to be POST, and the query or mutation needs to be placed in the request body. A new feature we learned about in React Query is the ability to trigger queries when the user interacts with the app using the enabled option.

We refactored the app to use Apollo Client, which is a specialized GraphQL client. It is very similar to React Query in that it has useQuery and useMutation hooks and a provider component. One advantage over React Query is that Apollo Client interacts directly with the GraphQL API, which means we write less code.

In the next chapter, we will cover patterns that help us build...

Questions

Answer the following questions to check what you have learned in this chapter:

  1. The following is an attempt at a GraphQL query to get a GitHub viewer’s name and email address:
    viewer: {
      name,
      email
    }

The query errors though – what is the problem?

  1. What is the mutation that would unstar a GitHub repository? The mutation should have a parameter for the repository ID.
  2. The following use of fetch is an attempt to call a GraphQL API:
    const response = await fetch(process.env.REACT_APP_API_URL!, {
      body: JSON.stringify({
        query: GET_DATA_QUERY,
      }),
    });

This doesn’t work though – what is the problem?

  1. Where does the authorization access token in a protected GraphQL API get specified when using Apollo Client?
  2. A component uses Apollo Client’s useQuery hook to fetch data from a GraphQL API, but the component errors with the following error:
...

Answers

  1. The query syntax is incorrect – the syntax is like JSON but doesn’t have colons and commas. Also, the query keyword can be omitted, but it is best practice to include this. Here is the corrected query:
    query {
      viewer {
        name
        email
      }
    }
  2. The following mutation will unstar a GitHub repository:
    mutation ($repoId: ID!) {
      removeStar(input: { starrableId: $repoId }) {
        starrable {
          stargazers {
            totalCount
          }
        }
      }
    }
  3. The request is missing the HTTP POST method:
    const response = await fetch(process.env.REACT_APP_API_URL!, {
      method: 'POST',
      body: JSON.stringify({
        query: GET_DATA_QUERY,
      }),
    });
  4. The authorization access token gets specified when Apollo Client...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn React with TypeScript - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781804614204
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Carl Rippon

Carl Rippon has been in the software industry for over 20 years developing a complex lines of business applications in various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies including Angular, ReactJS, and TypeScript. Carl has also written over 100 blog posts on various technologies.
Read more about Carl Rippon