Reader small image

You're reading from  React and React Native - Fourth Edition

Product typeBook
Published inMay 2022
Reading LevelIntermediate
PublisherPackt
ISBN-139781803231280
Edition4th Edition
Languages
Right arrow
Authors (3):
Adam Boduch
Adam Boduch
author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

Roy Derks
Roy Derks
author image
Roy Derks

Roy Derks is a serial start-up CTO, international speaker, and author from the Netherlands. He has been working with React, React Native, and GraphQL since 2016. You might know him from the book “React Projects – Second Edition”, which was released by Packt earlier this year. Over the last few years, he has inspired tens of thousands of developers worldwide through his talks, books, workshops, and courses.
Read more about Roy Derks

Mikhail Sakhniuk
Mikhail Sakhniuk
author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

View More author details
Right arrow

Chapter 31: Building a GraphQL React App

In the previous chapter, you received an extensive introduction to Apollo and GraphQL and learned why and how you should use this approach for your React application.

Now, you can build your Todo React application using Apollo Client. By the end of this chapter, you should be comfortable with knowing how data moves around in a GraphQL-centric application.

In this chapter, we'll cover the following topics:

  • Todo and Apollo Client
  • The GraphQL schema
  • Bootstrapping Apollo Client
  • Adding to-do items
  • Rendering to-do items
  • Completing to-do items

Technical requirements

You can find the code files present in this chapter on GitHub at https://github.com/PacktPublishing/React-and-React-Native-4th-Edition/tree/main/Chapter31.

Creating a Todo app

In this chapter, we'll build a Todo example for React that uses GraphQL to handle its data. This example is based on a popular open source library (https://todomvc.com/examples/react/), which is a robust, yet concise, starting point for creating the Todo application for this chapter.

I'm going to walk you through an example React implementation of a Todo app. Also, you can find a React Native implementation of this same web app in the GitHub repository for this chapter. The key is that the mobile version will use the same GraphQL backend as the web UI. I think this is a win for React developers who want to build both web and native versions of their apps as they can share the same schema!

The code for this chapter contains both a web version build with React and a native version with React Native. If you've worked on frontend development in the past 5 years, you've probably come across a sample Todo app. Here's what the web version...

Constructing a GraphQL schema

The schema is the vocabulary used by the GraphQL backend server and the Apollo Client implementation in the frontend. The GraphQL type system enables the schema to describe the data that's available and how to put it all together when a query request comes in. This is what makes the whole approach so scalable – the fact that the GraphQL runtime figures out how to put data together. All you need to supply are functions that tell GraphQL where the data is – for example, in a database or a remote service endpoint.

Let's take a look at some of the types used in the GraphQL schema for the Todo app. We'll start with Todo itself:

type Todo { 
  id: ID!
  text: String! 
  complete: Boolean
}

This type describes the Todo objects used throughout the application, including all the optional and required fields for this type. In the example code, you can see that the types followed with an exclamation...

Bootstrapping the Apollo Client

At this point, you will have the GraphQL backend up and running. Now, you can focus on your React components in the frontend. In particular, you're going to look at the Apollo Client in a React application. In web apps, it's usually React Router that bootstraps Apollo Client. Let's now look at the src/index.js file that serves as the entry point for your web app:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { ApolloClient, InMemoryCache, ApolloProvider } from
  '@apollo/client';
import App from './App';
import './index.css';
const client = new ApolloClient({
  cache: new InMemoryCache(),
  uri: 'http://localhost:4000/graphql',
});
 
const root =
  ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <ApolloProvider client...

Adding todo items

In the App component, there's also a text input that allows the user to enter new todo items. When they're done entering the todo item, Apollo Client will need to send a mutation to the backend GraphQL server. Here's what the component code looks like:

function App() {
  const [addTodo] = useMutation(ADD_TODO, {
    refetchQueries: [
      {
        query: GET_USER,
        variables: {
          userId: 'me',
        },
      },
    ],
  });
  return (
    <div>
      <section className='todoapp'>
        <header className=&apos...

Rendering todo items

It's the job of the TodoList component to render the todo list items. When the GET_USER query takes place, the TodoList component needs to be able to render all the todo items. Let's take a look at the item list again, with several more todos added.

Figure 31.4 – The Todos MVC app with the filled list

Here's the TodoList component itself:

import React from 'react';
import { useMutation } from '@apollo/client';
import Todo from './Todo';
import { MARK_ALL_TODOS, GET_USER } from '../constants';
function TodoList({ user: { todos, totalCount,
  completedCount } }) {
  const [markAllTodos] = useMutation(MARK_ALL_TODOS, {
    refetchQueries: [{ query: GET_USER, variables: 
      { userId: 'me' } }],
  });
  const handleMarkAllChange = () => {
    if (todos)...

Completing todo items

The last piece of this application is rendering each todo item and providing the ability to change the status of the todo in the Todo component in src/components/Todo.js. Let's look at pieces of this code:

import classnames from 'classnames';
import { useMutation } from '@apollo/client';
import {
  CHANGE_TODO_STATUS,
  REMOVE_TODO,
  GET_USER,
} from '../constants';
function Todo({ todo }) {
  const [changeTodoStatus] =
    useMutation(CHANGE_TODO_STATUS, {
    refetchQueries: [{ query: GET_USER, variables: 
      { userId: 'me' } }],
  });
  const [removeTodo] = useMutation(REMOVE_TODO, {
    refetchQueries: [{ query: GET_USER, variables: 
      { userId: 'me' } }],
  });
  const handleCompleteChange = (e...

Summary

In this chapter, you implemented some specific GraphQL and Apollo Client ideas. Starting with the GraphQL schema, you learned how to declare the data that's used by the application and how these data types resolve to specific data sources, such as API endpoints. Then, you learned about bootstrapping GraphQL queries with Apollo Client in a React app. Next, you walked through the specifics of adding, changing, and listing todo items. The application itself uses the same schema as the web version of the Todo application, which makes things much easier when you're developing web and native React applications.

Well, that's a wrap for this book. We've gone over a lot of material together, and I hope that you've learned as much from reading it as I have from writing it. If there is one theme from this book that you should walk away with, it's that React is simply a rendering abstraction. As new rendering targets emerge, new React libraries will emerge...

Further reading

Refer to the following link for more information:

Why subscribe?

  • Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
  • Improve your learning with Skill Plans built especially for you
  • Get a free eBook or video every month
  • Fully searchable for easy access to vital information
  • Copy and paste, print, and bookmark content

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at customercare@packtpub.com for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React and React Native - Fourth Edition
Published in: May 2022Publisher: PacktISBN-13: 9781803231280
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 €14.99/month. Cancel anytime

Authors (3)

author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

author image
Roy Derks

Roy Derks is a serial start-up CTO, international speaker, and author from the Netherlands. He has been working with React, React Native, and GraphQL since 2016. You might know him from the book “React Projects – Second Edition”, which was released by Packt earlier this year. Over the last few years, he has inspired tens of thousands of developers worldwide through his talks, books, workshops, and courses.
Read more about Roy Derks

author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk