Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Full-Stack Web Development with GraphQL and React
Full-Stack Web Development with GraphQL and React

Full-Stack Web Development with GraphQL and React: Taking React from frontend to full-stack with GraphQL and Apollo , Second Edition

eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Full-Stack Web Development with GraphQL and React

Chapter 1: Preparing Your Development Environment

The application we are going to build in this book will be a simplified version of Facebook, called Graphbook. We will allow our users to sign up and log in to read and write posts and chat with friends, similar to what we can do on common social networks.

When developing an application, being well-prepared is always a requirement. However, before we start, we need to put our stack together. In this chapter, we will explore whether our techniques work well with our development process, what we need before getting started, and which tools can help us when building software.

This chapter explains the architecture for our application by going through the core concepts, the complete process, and preparing for a working React setup.

This chapter covers the following topics:

  • Architecture and technology
  • Thinking critically about how to architect a stack
  • Building the React and GraphQL stack
  • Installing and configuring Node.js
  • Setting up a React development environment with webpack, Babel, and other requirements
  • Debugging React applications using Chrome DevTools and React Developer Tools

Technical requirements

The source code for this chapter is available in the following GitHub repository: https://github.com/PacktPublishing/Full-Stack-Web-Development-with-GraphQL-and-React-Second-Edition/tree/main/Chapter01.

Understanding the application architecture

Since its initial release in 2015, GraphQL has become the new alternative to the standard SOAP and REST APIs. GraphQL is a specification, like SOAP and REST, that you can follow to structure your application and data flow. It is so innovative because it allows you to query specific fields of entities, such as users and posts. This functionality makes it very good for targeting multiple platforms at the same time. Mobile apps may not need all the data that's displayed inside the browser on a desktop computer. The query you send consists of a JSON-like object that defines which information your platform requires. For example, a query for a post may look like this:

post {
  id
  text
  user {
    user_id
    name
  } 
}

GraphQL resolves the correct entities and data, as specified in your query object. Every field in GraphQL represents a function that resolves to a value. Those functions are called Resolver functions. The return value could be just the corresponding database value, such as the name of a user, or it could be a date, which is formatted by your server before returning it.

GraphQL is completely database agnostic and can be implemented in any programming language. To skip the step of implementing a GraphQL library, we are going to use Apollo, which is a GraphQL server for the Node.js ecosystem. Thanks to the team behind Apollo, this is very modular. Apollo works with many of the common Node.js frameworks, such as Hapi, Koa, and Express.js.

We are going to use Express.js as our basis because it is used on a wide scale in the Node.js and GraphQL communities. GraphQL can be used with multiple database systems and distributed systems to offer a straightforward API over all your services. It allows developers to unify existing systems and handle data fetching for client applications.

How you combine your databases, external systems, and other services into one server backend is up to you. In this book, we are going to use a MySQL server via Sequelize as our data storage. SQL is the most well-known and commonly used database query language, and with Sequelize, we have a modern client library for our Node.js server to connect with our SQL server.

HTTP is the standard protocol for accessing a GraphQL API. It also applies to Apollo Servers. However, GraphQL is not fixed to one network protocol. Everything we have mentioned so far is everything important for the backend.

When we get to the frontend of our Graphbook application, we are mainly going to use React. React is a JavaScript UI framework that was released by Facebook that has introduced many techniques that are now commonly used for building interfaces on the web, as well as on native environments.

Using React comes with a bunch of significant advantages. When building a React application, you always split your code into many components, targeting their efficiency and ability to be reused. Of course, you can do this without using React, but it makes it very easy. Furthermore, React teaches you how to update application states, as well as the UI, reactively. You never update the UI and then the data separately.

React makes rerendering very efficient by using a virtual DOM, which compares the virtual and actual DOM and updates it accordingly. Only when there is a difference between the virtual and real DOM does React apply these changes. This logic stops the browser from recalculating the layout, Cascading Style Sheets (CSS), and other computations that negatively impact the overall performance of your application.

Throughout this book, we are going to use the Apollo client library. It naturally integrates with React and our Apollo Server.

If we put all this together, the result is the main stack consisting of Node.js, Express.js, Apollo, SQL, Sequelize, and React.

The basic setup

The basic setup for making an application work is the logical request flow, which looks as follows:

Figure 1.1 – Logical request workflow

Figure 1.1 – Logical request workflow

Here is how the logical request flow works:

  1. The client requests our site.
  2. The Express.js server handles these requests and serves a static HTML file.
  3. The client downloads all the necessary files, according to this HTML file. The files also include a bundled JavaScript file.
  4. This bundled JavaScript file is our React application. After executing all the JavaScript code from this file, all the required Ajax alias GraphQL requests are made to our Apollo Server.
  5. Express.js receives the requests and passes them to our Apollo endpoint.
  6. Apollo queries all the requested data from all the available systems, such as our SQL server or third-party services, merges the data, and sends it back as JSON.
  7. React can render the JSON data as HTML.

This workflow is the basic setup for making an application work. In some cases, it makes sense to offer server-side rendering for our client. The server would need to render and send all XMLHttpRequests itself before returning the HTML to the client. The user will save doing one or more round trips if the server sends the requests on the initial load. We will focus on this topic later in this book, but that is the application architecture in a nutshell. With that in mind, let's get hands-on and set up our development environment.

Installing and configuring Node.js

The first step of preparing our project is to install Node.js. There are two ways to do this:

  • One option is to install Node Version Manager (NVM). The benefit of using NVM is that you can easily run multiple versions of Node.js side by side, which handles the installation process for you on nearly all UNIX-based systems, such as Linux and macOS. Within this book, we do not need the option to switch between different versions of Node.js.
  • The other option is to install Node.js via the package manager of your distribution if you are using Linux. The official PKG file is for Mac, while the MSI file is for Windows. We are going to use the regular Linux package manager for this book as it is the easiest method.

    Note

    You can find the Downloads section of Node.js at the following link: https://nodejs.org/en/download/.

We are going to be using the second option here. It covers the regular server configurations and is easy to understand. I will keep this as short as possible and skip all the other options, such as Chocolatey for Windows and Brew for Mac, which are very specialized for those specific operating systems.

I assume that you are using a Debian-based system for ease of use with this book. It has got the normal APT package manager and repositories for easily installing Node.js and MySQL. If you are not using a Debian-based system, you can look up the matching commands to install Node.js at https://nodejs.org/en/download/package-manager/.

Our project is going to be new so that we can use Node.js 14, which is the current LTS version:

  1. First, let's add the correct repository for our package manager by running the following command:
    curl -fsSL https://deb.nodesource.com/setup_14.x | sudo bash -
  2. Next, we must install Node.js and the build tools for native modules using the following command:
    apt-get install -y nodejs build-essential
  3. Finally, let's open a Terminal and verify that the installation was successful:
    node --version

    Note

    Installing Node.js via the package manager will automatically install npm.

Great! You are now set to run server-side JavaScript with Node.js and install Node.js modules for your projects with npm.

All the dependencies that our project relies on are available at https://npmjs.com and can be installed with npm or Yarn. We will rely on npm as it is more widely used than Yarn. So, let's continue and start using npm to set up our project and its dependencies.

Setting up React

The development environment for our project is ready. In this section, we are going to install and configure React, which is the primary aspect of this chapter. Let's start by creating a new directory for our project:

mkdir ~/graphbook
cd ~/graphbook

Our project will use Node.js and many npm packages. We will create a package.json file to install and manage all the dependencies for our project. It stores information about the project, such as the version number, name, dependencies, and much more.

Just run npm init to create an empty package.json file:

npm init

npm will ask some questions, such as asking for the package name, which is, in fact, the project name. Enter Graphbook to insert the name of your application in the generated package.json file.

I prefer to start with version number 0.0.1 since the default version number that npm offers with 1.0.0 represents the first stable release for me. However, it is your choice regarding which version you use here.

You can skip all the other questions by pressing the Enter key to save the default values of npm. Most of them are not relevant because they just provide information such as a description or the link to the repository. We are going to fill in the other fields, such as the scripts, while working through this book. You can see an example of the command line in the following screenshot:

Figure 1.2 – npm project setup

Figure 1.2 – npm project setup

The first and most crucial dependency for this book is React. Use npm to add React to our project:

npm install --save react react-dom

This command installs two npm packages from https://npmjs.com into our project folder under node_modules.

npm automatically edited our package.json file since we provided the --save option and added those packages with the latest available version numbers.

You might be wondering why we installed two packages, even though we only needed React. The react package only provides React-specific methods. All React Hooks, such as componentDidMount, useState, and even React's component class, come from this package. You need this package to write any React application.

In most cases, you won't even notice that you have used react-dom. This package offers all the functions to connect the actual DOM of the browser to your React application. Usually, you use ReactDOM.render to render your application at a specific point in your HTML and only once in your code. We will cover how to render React later in this book.

There is also a function called ReactDOM.findDOMNode, which gives you direct access to a DOMNode, but I strongly discourage using this since any changes on DOMNodes are not available in React itself. I have never needed to use this function, so try to avoid it if possible. Now, that our npm project has been set up and the two main dependencies have been installed, we need to prepare an environment that bundles all the JavaScript files we are going to write. We will focus on this in the next section.

Preparing and configuring webpack

Our browser requests an index.html file when accessing our application. It specifies all the files that are required to run our application. We need to create this index.html file, which we serve as the entry point of our application:

  1. Create a separate directory for our index.html file:
    mkdir public
    cd public
    touch index.html
  2. Then, save this inside index.html:
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, 
           initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Graphbook</title>
      </head>
      <body>
        <div id="root"></div>
      </body>
    </html>

As you can see, no JavaScript is loaded here. There is only one div tag with the root ID. This div tag is the DOMNode that our application will be rendered in by ReactDOM.

So, how do we get React up and running with this index.html file?

To accomplish this, we need to use a web application bundler, which will prepare and bundle all our application assets. All the required JavaScript files and node_modules are bundled and minified; SASS and SCSS preprocessors are transpiled to CSS, as well as being merged and minified.

A few application bundler packages are available, including webpack, Parcel, and Gulp. For our use case, we will use webpack. It is the most common module bundler and has a large community surrounding it. To bundle our JavaScript code, we need to install webpack and all its dependencies, as follows:

npm install --save-dev @babel/core babel-loader @babel/preset-env @babel/preset-react clean-webpack-plugin css-loader file-loader html-webpack-plugin style-loader url-loader webpack webpack-cli webpack-dev-server

This command adds all the development tools to devDependencies in the package.json file. We will need these to bundle our application. They are only installed in a development environment and are skipped in production.

If you are not already aware, setting up webpack can be a bit of a hassle. Many options can interfere with each other and lead to problems when you're bundling your application. Now, let's create a webpack.client.config.js file in the root folder of your project.

Enter the following code:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const buildDirectory = 'dist';
const outputDirectory = buildDirectory + '/client';
module.exports = {
  mode: 'development',
  entry: './src/client/index.js',
  output: {
    path: path.join(__dirname, outputDirectory),
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }, 
  devServer: {
    port: 3000,
    open: true
  },
  plugins: [
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [path.join(__dirname, 
      buildDirectory)]
    }),
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
};

The webpack configuration file is just a regular JavaScript file where you can require node_modules and custom JavaScript files. This is the same as everywhere else inside Node.js. Let's quickly go through all of the main properties of this configuration. Understanding these will make future custom webpack configs much easier. All the important points are explained here:

  • HtmlWebpackPlugin: This automatically generates an HTML file that includes all the webpack bundles. We pass our previously created index.html as a template.
  • CleanWebpackPlugin: This empties all of the provided directories to clean the old build files. The cleanOnceBeforeBuildPatterns property specifies an array of folders that are cleaned before the build process is started.
  • The entry field tells webpack where the starting point of our application is. This file needs to be created by us.
  • The output object specifies how our bundle is called and where it should be saved. For us, this is dist/client/bundle.js.
  • Inside module.rules, we match our file extensions with the correct loaders. All the JavaScript files (except those located in node_modules) are transpiled by Babel as specified by babel-loader so that we can use ES6 features inside our code. Our CSS gets processed by style-loader and css-loader. There are many more loaders for JavaScript, CSS, and other file extensions available.
  • The devServer feature of webpack enables us to run the React code directly. This includes hot reloading code in the browser without rerunning a build or refreshing the browser tab.

    Note

    If you need a more detailed overview of the webpack configuration, have a look at the official documentation: https://webpack.js.org/concepts/.

With this in mind, let's move on. We are missing the src/client/index.js file from our webpack configuration, so let's create it, as follows:

mkdir -p src/client
cd src/client
touch index.js

You can leave this file empty for the moment. It can be bundled by webpack without content inside. We are going to change it later in this chapter.

To spin up our development webpack server, we will add a command to package.json that we can run using npm.

Add the following line to the scripts object inside package.json:

"client": "webpack serve --devtool inline-source-map --hot --config webpack.client.config.js"

Now, execute npm run client in your console and watch how a new browser window opens. We are running webpack serve with the newly created configuration file.

Sure, the browser is still empty, but if you inspect the HTML with Chrome DevTools, you will see that we have already got a bundle.js file and that our index.html file was taken as a template.

With that, we've learned how to include our empty index.js file with the bundle and serve it to the browser. Next, we'll render our first React component inside our template index.html file.

Rendering your first React component

There are many best practices for React. The central philosophy behind it is to split our code into separate components where possible. We are going to cover this approach in more detail in Chapter 5, Reusable React Components and React Hooks.

Our index.js file is the main starting point of our frontend code, and this is how it should stay. Do not include any business logic in this file. Instead, keep it as clean and slim as possible.

The index.js file should include the following code:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App/>, document.getElementById('root'));

The release of ECMAScript 2015 introduced the import feature. We can use it to load our npm packages – react and react-dom – and our first custom React component, which we must write now.

Of course, we need to cover the traditional Hello World program.

Create the App.js file next to your index.js file and ensure it contains the following content:

import React from 'react';
const App = () => {
    return (
        <div>Hello World!</div>
    )
}
export default App

Here, we exported a single stateless function called App that is then imported by the index.js file. As we explained previously, we are now actively using ReactDOM.render in our index.js file.

The first parameter of ReactDOM.render is the component or function that we want to render, which is the exported function displaying the Hello World! message. The second parameter is the browser's DOMNode, where it should render. We receive DOMNode with a plain document.getElementById JavaScript.

We defined our root element when we created the index.html file. After saving the App.js file, webpack will try to build everything again. However, it should not be able to do that. webpack will encounter a problem when bundling our index.js file because of the <App /> tag syntax we are using in the ReactDOM.render method. It was not transpiled to a normal JavaScript function.

We configured webpack to load Babel for our JavaScript file but did not tell Babel what to transpile and what not to transpile.

Let's create a .babelrc file in the root folder that contains the following content:

{
  "presets": ["@babel/env","@babel/react"]
}

Note

You may have to restart the server because the .babelrc file is not reloaded when changes are made to the file. After a few moments, you should see the standard Hello World! message in your browser.

Here, we told Babel to use @babel/preset-env and @babel/preset-react, which we installed together with webpack. These presets allow Babel to transform specific syntax, such as JSX. We can use those presets to create normal JavaScript that all browsers can understand and that webpack can bundle.

Rendering arrays from React state

Hello World! is a must for every good programming book, but this is not what we are aiming for when we use React.

A social network such as Facebook or Graphbook, which we are writing now, needs a newsfeed and an input to post news. Let's implement this.

Since this is the first chapter of this book, we will do this inside App.js.

We should work with some fake data here since we have not set up our GraphQL API yet. We can replace this with real data later.

Define a new variable above the default exported App function, like this:

const initialPosts = [
    {
        id: 2,
        text: 'Lorem ipsum',
        user: {
        avatar: '/uploads/avatar1.png',
        username: 'Test User'
        }
    },
    {
        id: 1,
        text: 'Lorem ipsum',
        user: {
        avatar: '/uploads/avatar2.png',
        username: 'Test User 2'
        }
    }
];

We are going to render these two fake posts in React. To prepare this, change the first line of the App.js file to the following:

import React, { useState } from 'react';

This ensures that the useState function of React is imported and accessible by our stateless function.

Replace the current content of your App function with the following code:

const [posts, setPosts] = useState(initialPosts);
return (
  <div className="container">
    <div className="feed">
      { initialPosts.map((post, i) => 
        <div key={post.id} className="post">
          <div className="header">
            <img src={post.user.avatar} />
            <h2>{post.user.username}</h2>
          </div>
          <p className="content">
            {post.text}
          </p>
        </div>
      )}
    </div>
  </div>
)

Here, we initiated a posts array inside the function via the React useState function. It allows us to have a state without writing a real React class; instead, it only relies on raw functions. The useState function expects one parameter, which is the initial value of the state variable. In this case, this is the constant initialPosts array. This returns the posts state variable and a setPosts function, which you can use to update the local state.

Then, we iterated over the posts array with the map function, which again executes the inner callback function, passing each array item as a parameter one by one. The second parameter is just called i and represents the index of the array element we are processing. Everything that's returned from the map function is then rendered by React.

We merely returned HTML by putting each post's data in ES6 curly braces. These curly braces tell React to interpret and evaluate the code inside them as JavaScript.

As shown in the preceding code, we are relying on the posts that were returned by the useState function. This data flow is very convenient because we can update the state at any point in our application and the posts will rerender. The important thing is that this will only work by using the setPosts function and passing the updated array to it. In this case, React notices the change of state and rerenders the function.

The preceding method is much cleaner, and I recommend this for readability purposes. When saving, you should be able to see rendered posts. They should look like this:

Figure 1.3 – Unstyled demo posts

Figure 1.3 – Unstyled demo posts

The images I am using here are freely available. You can use any other material that you have got if the path matches the string from the posts array. You can find those images in the official GitHub repository for this book.

CSS with webpack

The posts in the preceding figure have not been designed yet. I have already added CSS classes to the HTML our component returns.

Instead of using CSS to make our posts look better, another method is to use CSS-in-JS using packages such as styled components, which is a React package. Other alternatives include Glamorous and Radium. There are numerous reasons for and against using such libraries. With those other tools, you are not able to use SASS, SCSS, or LESS effectively. I need to work with other people, such as screen and graphics designers, who can provide and use CSS, but do not program styled components. There is always a prototype or existing CSS that can be used, so why should I spend time translating this into styled components CSS when I could just continue with standard CSS?

There is no right or wrong option here; you are free to implement the styling in any way you like. However, in this book, we will keep using good old CSS.

What we have already done in our webpack.client.config.js file is specify a CSS rule, as shown in the following code snippet:

{
  test: /\.css$/,
  use: ['style-loader', 'css-loader'],
},

style-loader injects your bundled CSS right into the DOM. css-loader will resolve all import or url occurrences in your CSS code.

Create a style.css file in /assets/css and fill in the following:

body {
  background-color: #f6f7f9;
  margin: 0;
  font-family: 'Courier New', Courier, monospace
}
p {
  margin-bottom: 0;
}
.container {
  max-width: 500px;
  margin: 70px auto 0 auto;
}
.feed {
  background-color: #bbb;
  padding: 3px;
  margin-top: 20px;
}
.post {
  background-color: #fff;
  margin: 5px;
}
.post .header {
  height: 60px;
}
.post .header > * {
  display: inline-block;
  vertical-align: middle;
}
.post .header img {
  width: 50px;
  height: 50px;
  margin: 5px;
}
.post .header h2 {
  color: #333;
  font-size: 24px;
  margin: 0 0 0 5px;
}
.post p.content {
  margin: 5px;
  padding: 5px;
  min-height: 50px;
}

Refreshing your browser will leave you with the same old HTML you had previously.

This problem occurs because webpack is a module bundler and does not know anything about CSS; it only knows JavaScript. We must import the CSS file somewhere in our code.

Instead of using index.html and adding a head tag, we can use webpack and our CSS rule to load it right into App.js. This solution is very convenient since all the required CSS throughout our application gets minified and bundled. Webpack automates this process.

In your App.js file, add the following behind the React import statement:

import '../../assets/css/style.css';

webpack magically rebuilds our bundle and refreshes our browser tab.

With that, you have successfully rendered fake data via React and styled it with bundled CSS from webpack. It should look something like this:

Figure 1.4 – Styled demo posts

Figure 1.4 – Styled demo posts

The output looks very good already.

Event handling and state updates with React

For this project, it would be great to have a simple textarea where we can click a button and then add a new post to the static posts array we wrote in the App function.

Add the following code above the div tag that contains the feed class:

<div className="postForm">
  <form onSubmit={handleSubmit}>                      
    <textarea value={postContent} onChange={(e) => 
      setPostContent(e.target.value)}
      placeholder="Write your custom post!"/>
    <input type="submit" value="Submit" />
  </form>
</div>

You can use forms in React without any problems. React can intercept the submit event of requests by giving the form an onSubmit property, which will be a function to handle the logic.

We are passing the postContent variable to the value property of textarea to get what is called a controlled input.

Create an empty string variable to save the textarea value by using the useState function from React:

const [postContent, setPostContent] = useState('');

The postContent variable is already being used for our new textarea since we specified it in the value property. Furthermore, we directly implemented the setPostContent function in our post form. This is used for the onChange property or any event that is called whenever you type inside textarea. The setPostContent function receives the e.target.value variable, which is the DOM accessor for the value of textarea, which is then stored in the state of the React function.

Look at your browser again. The form is there, but it is not pretty, so add the following CSS:

form {
  padding-bottom: 20px;
}
form textarea {
  width: calc(100% - 20px);
  padding: 10px;
  border-color: #bbb;
}
form [type=submit] {
  border: none;
  background-color: #6ca6fd;
  color: #fff;
  padding: 10px;
  border-radius: 5px;
  font-size: 14px;
  float: right;
}

The last step is to implement the handleSubmit function for our form. Add it straight after the state variables and the return statement:

const handleSubmit = (event) => {
    event.preventDefault();
    const newPost = {
        id: posts.length + 1,
        text: postContent,
        user: {
            avatar: '/uploads/avatar1.png',
            username: 'Fake User'
        }
    };
    setPosts([newPost, ...posts]);
    setPostContent('');
};

The preceding code looks more complicated than it is, but I am going to explain it quickly.

We needed to run event.preventDefault to stop our browser from actually trying to submit the form and reload the page. Most people that come from jQuery or other JavaScript frameworks will know this.

Next, we saved our new post in the newPost variable, which we want to add to our feed.

We faked some data here to simulate a real-world application. For our test case, the new post ID is the number of posts in our state variable plus one. React wants us to give every child in the ReactDOM a unique ID. By counting the number of posts with posts.length, we simulate the behavior of a real backend giving us unique IDs for our posts.

The text for our new post comes from the postContent state variable.

Furthermore, we do not have a user system right now that our GraphQL server can use to give us the newest posts, including the matching users and their avatars. We can simulate this by having a static user object for all the new posts we create.

Finally, we updated the state again. We did this by using the setPosts function and passing a merged array consisting of the new posts and the current posts array with a destructuring assignment. After that, we cleared textarea by passing an empty string to the setPostContent function.

Now, go ahead and play with your working React form. Do not forget that all the posts you create do not persist since they are only held in the local memory of the browser and are not saved to a database. Consequently, refreshing deletes your posts.

Controlling document heads with React Helmet

When developing a web application, you must control your document heads. You might want to change the title or description, based on the content you are presenting.

React Helmet is a great package that offers this on the fly, including overriding multiple headers and server-side rendering. Let's see how we can do this:

  1. Install React Helmet with the following command:
    npm install --save react-helmet

    You can add all standard HTML headers with React Helmet.

    I recommend keeping standard head tags inside your template. This has the advantage that, before React has been rendered, there is always the default document head. For our case, you can directly apply a title and description in App.js.

  2. Import react-helmet at the top of the file:
    import { Helmet } from 'react-helmet';
  3. Add Helmet directly above postForm div:
    <Helmet>
      <title>Graphbook - Feed</title>
      <meta name="description" content="Newsfeed of all
        your friends on Graphbook" />
    </Helmet>

If you reload the browser and watch the title on the tab bar of your browser carefully, you will see that it changes from Graphbook to Graphbook - Feed. This behavior happens because we already defined a title inside index.html. When React finishes rendering, the new document head is applied.

Production build with webpack

The last step for our React setup is to have a production build. Until now, we were only using webpack-dev-server, but this naturally includes an unoptimized development build. Furthermore, webpack automatically spawns a web server. In the next chapter, we will introduce Express.js as our web server so that we don't need webpack to start it.

A production bundle does merge all JavaScript files, but it also merges all the CSS files into two separate files. Those can be used directly in the browser. To bundle CSS files, we will rely on another webpack plugin, called MiniCss:

npm install --save-dev mini-css-extract-plugin

We do not want to change the current webpack.client.config.js file because it is made for development work. Add the following command to the scripts object of your package.json:

"client:build": "webpack --config webpack.client.build.config.js"

This command runs webpack using an individual production webpack config file. Let's create this one. First, clone the original webpack.client.config.js file and rename it webpack.client.build.config.js.

Change the following things in the new file:

  1. mode needs to be production, not development.
  2. Require the MiniCss plugin:
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');
  3. Replace the current CSS rule:
    {
      test: /\.css$/,
      use: [{ loader: MiniCssExtractPlugin.loader,
        options: {
          publicPath: '../'
        }
     }, 'css-loader'],
    },

    We are no longer using style-loader; instead, we're using the MiniCss plugin. The plugin goes through the complete CSS code, merges it into a separate file, and removes the import statements from the bundle.js file, which we generate in parallel.

  4. Lastly, add the plugin to the plugins at the bottom of the configuration file:
    new MiniCssExtractPlugin({
      filename: 'bundle.css',
    })
  5. Remove the entire devServer property.

When you run the new configuration, it won't spawn a server or browser window; it will only create a production JavaScript and CSS bundle and will require them in our index.html file. According to our webpack.client.build.config.js file, those three files are going to be saved to the dist/client folder.

You can run this command by executing npm run client:build.

If you look in the dist/client folder, you will see three files. You can open the index.html file in your browser. Sadly, the images are broken because the image URLs are not correct anymore. We must accept this for the moment because it will be automatically fixed when we have a working backend.

With that, we have finished the basic setup for React.

Useful development tools

When you're working with React, you want to know why your application rendered the way that it did. You need to know which properties your components received and how their current state looks. Since this is not displayed in the DOM or anywhere else in Chrome DevTools, you need a separate plugin.

Fortunately, Facebook has got you covered. Visit https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi and install React Developer Tools. This plugin allows you to inspect React applications and components. When you open Chrome DevTools again, you will see that there are two new tabs at the end of the row – one called Components and another called Profiler:

Figure 1.5 – React developer tools

Figure 1.5 – React developer tools

You will only be able to see those tabs if you are running a React application in development mode. If a React application is running or bundled in production, those extensions won't work.

Note

If you are unable to see this tab, you may need to restart Chrome completely. You can also find React Developer Tools for Firefox.

The first tab allows you to view, search, and edit all the components of your ReactDOM.

The left-hand side panel looks much like the regular DOM tree (Elements) in Chrome DevTools, but instead of showing HTML markup, you will see all the components you used inside a tree. ReactDOM rendered this tree into real HTML, as follows:

Figure 1.6 – React component tree

Figure 1.6 – React component tree

The first component in the current version of Graphbook should be <App />.

By clicking a component, your right-hand side panel will show its properties, state, and context. You can try this with the App component, which is the only real React component:

Figure 1.7 – React component state

Figure 1.7 – React component state

The App function is the first component of our application. This is the reason why it received no props. Children can receive properties from their parents; with no parent, there are no props.

Now, test the App function and play around with the state. You will see that changing it rerenders your ReactDOM and updates the HTML. You can edit the postContent variable, which inserts the new text inside textarea. As you will see, all the events are thrown, and your handler runs. Updating the state always triggers a rerender, so try to update the state as little as possible to use as few computing resources as possible.

Summary

In this chapter, we set up a working React environment. This is a good starting point for our frontend as we can write and build static web pages with this setup.

The next chapter will primarily focus on our setup for the backend. We will configure Express.js to accept our first requests and pass all GraphQL queries to Apollo. Furthermore, you will learn how to use Postman to test your API.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build full-stack applications with modern APIs using GraphQL and React Hooks
  • Integrate Apollo into React and build frontend components using GraphQL
  • Implement a self-updating notification pop-up with a unique GraphQL feature called Subscriptions

Description

React and GraphQL, when combined, provide you with a very dynamic, efficient, and stable tech stack to build web-based applications. GraphQL is a modern solution for querying an API that represents an alternative to REST and is the next evolution in web development. This book guides you in creating a full-stack web application from scratch using modern web technologies such as Apollo, Express.js, Node.js, and React. First, you’ll start by configuring and setting up your development environment. Next, the book demonstrates how to solve complex problems with GraphQL, such as abstracting multi-table database architectures and handling image uploads using Sequelize. You’ll then build a complete Graphbook from scratch. While doing so, you’ll cover the tricky parts of connecting React to the backend, and maintaining and synchronizing state. In addition to this, you’ll also learn how to write Reusable React components and use React Hooks. Later chapters will guide you through querying data and authenticating users in order to enable user privacy. Finally, you’ll explore how to deploy your application on AWS and ensure continuous deployment using Docker and CircleCI. By the end of this web development book, you'll have learned how to build and deploy scalable full-stack applications with ease using React and GraphQL.

Who is this book for?

This React GraphQL book is for web developers familiar with React and GraphQL who want to enhance their skills and build full-stack applications using industry standards like React, Apollo, Node.js, and SQL at scale while learning to solve complex problems with GraphQL.

What you will learn

  • Build a GraphQL API by implementing models and schemas with Apollo and Sequelize
  • Set up an Apollo Client and build frontend components using React
  • Write Reusable React components and use React Hooks
  • Authenticate and query user data using GraphQL
  • Use Mocha to write test cases for your full-stack application
  • Deploy your application to AWS using Docker and CircleCI
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 28, 2022
Length: 472 pages
Edition : 2nd
Language : English
ISBN-13 : 9781801077880
Vendor :
ECMA International
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Product feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Feb 28, 2022
Length: 472 pages
Edition : 2nd
Language : English
ISBN-13 : 9781801077880
Vendor :
ECMA International
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 137.97
React Projects
$38.99
React and React Native
$49.99
Full-Stack Web Development with GraphQL and React
$48.99
Total $ 137.97 Stars icon
Banner background image

Table of Contents

16 Chapters
Section 1: Building the Stack Chevron down icon Chevron up icon
Chapter 1: Preparing Your Development Environment Chevron down icon Chevron up icon
Chapter 2: Setting Up GraphQL with Express.js Chevron down icon Chevron up icon
Chapter 3: Connecting to the Database Chevron down icon Chevron up icon
Section 2: Building the Application Chevron down icon Chevron up icon
Chapter 4: Hooking Apollo into React Chevron down icon Chevron up icon
Chapter 5: Reusable React Components and React Hooks Chevron down icon Chevron up icon
Chapter 6: Authentication with Apollo and React Chevron down icon Chevron up icon
Chapter 7: Handling Image Uploads Chevron down icon Chevron up icon
Chapter 8: Routing in React Chevron down icon Chevron up icon
Chapter 9: Implementing Server-Side Rendering Chevron down icon Chevron up icon
Chapter 10: Real-Time Subscriptions Chevron down icon Chevron up icon
Chapter 11: Writing Tests for React and Node.js Chevron down icon Chevron up icon
Section 3: Preparing for Deployment Chevron down icon Chevron up icon
Chapter 12: Continuous Deployment with CircleCI and AWS Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9
(8 Ratings)
5 star 25%
4 star 62.5%
3 star 0%
2 star 0%
1 star 12.5%
Filter icon Filter
Top Reviews

Filter reviews by




Poonam Jun 15, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
You can leave the lines you wrote above as well:This book is very helpful for elevating the existing tech stack. It offers in-depth knowledge of GraphQL with React library. From the installation of softwares to solving complex problems the book has everything, it also consists of practical examples which is the most important thing. Still in the process of reading it.
Amazon Verified review Amazon
Katie May 20, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This Sebastian is a good teacher, thanks for the second edition
Amazon Verified review Amazon
Nick Johnson Mar 13, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is an excellent little step-by-step tutorial. If you want to learn how to use GraphQL and React you could definitely do worse.It is aimed at people with no previous experience, so depending on your skill level you may find yourself skipping over the early sections that cover how to install Node and use NPM. It does go into some decent detail later on though. I learned.The code is pretty up to date. Functional components are used with hooks for state. As with all practical coding books, it'll be out of date in five years, but right now it's grand.As with all Packt books it's well presented and will look sweet on your shelves. A nice soft blue cover with orange accents. It's well made and doesn't fall apart.If this is a stack you need to pick up, reading this book will definitely set you on your way.
Amazon Verified review Amazon
Matt Williamson Apr 02, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I was originally going to give this book a 3 or a 4, BUT I kept reading. The React chapter was rough and I don't think it would help a beginner. I'll be honest, parts of this book were rough. For an author that talks about "modern" apps so much, there is a lot that is not modern at all. I would not expect to see "var" instead of "let" or for loops instead of map/forEach loops.If you are intermediate at React and have seen GraphQL a bit, then just keep going. This book has some real gems.One thing I've previously found challenging is implementing GraphQL schemas. This book made that easier to understand for me. Then they used Sequelize. As a user of Sequelize, I had to wonder why they chose it over any number of more modern ORMs. However, I did like that the book uses GraphQL connecting to a SQL db. I see this in real environments but not in too many tutorials.Another item that can be difficult is pagination, but the author walked us through a solution to a pagination problem pretty well. I definitely learned a bit there. The Auth section is also pretty good. Another gem is setting up an AWS S3 bucket to handle image uploads. Definitely a good touch there!What I found the most interesting, and what really bumped up the score for me, was the biggest gem of the book: manual SSR! Instead of using NextJS! This was really interesting and I read that part very closely. I finally understood why the author didn't start with create-react-app, as that would have been impossible for the manual SSR that was built. If you have the basics of React down, definitely take a look at this book.
Amazon Verified review Amazon
E. Leonard May 27, 2022
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
In reviewing this book I looked at both the physical and digital copies. Firstly I should say in the last few years the print quality of Packt has come on. The title gets it right with font-family choice, size, and of course, the code segments are clearly separated from the book text. I have no grumbles about the printed title. The binding seems to be on point and the book looks to be well enough made.Onto the content and we jump straight into setting up. The book bootstraps the project manually rather than using create-react-app CLI. I enjoyed this manual setup because it helps demystify it, highlights the pain in the rear that web pack can be and you’ll quite often see commercial projects which are not CRA-based apps. From this we go into a light dance around what react is and how to do some rendering basics. All standard stuff but so far so good.The next sections move on to the book project by way of introducing express.js and Apollo related packages to get graphQL up and running. Whereas many graphQL tutorials and books here will go with MongoDB/NoSQL here we use MySQL again this is in the book's favour as the commercial world at this point in time would say you’re still far likelier to bump into MySQL than MongoDB out there. The next chunk is working with the sequelize package covering creating, seeding, relationship types and migrations.The project itself is a chat/social app and while that is a common topic for portfolios and may lack originality it does cover a lot of the daily grind of tasks you will be expected to work on professionally, so it’s worth looking at the quality of the implementation rather than the originality of the app concept.The project itself uses AWS as we progress which requires sign-up and an active credit card, this will be off-putting to some which is understandable, but it makes the valid point that given the ubiquity of AWS in modern web development shops it’s a valid approach. It is worth noting that this may limit some people though.The SSR (server Side rendering) and Apollo with SSR is a stronger segment the book, the explanation is quite rich and this along with the following section on web sockets will take you into advanced features. The final run up is the obligatory deployment, here we’re using CircleCI and AWS. Deployment is the subject of entire books itself and therefore as a final segment its light, but it is informative enough and gives you what you need, or arms you with enough knowledge to go and hammer google with your questions.How could the book be better?1) It could have used typescript over javaScript as are and more commercial projects are going that way.2 )It could have been done as TDD (test-driven development), again, modern agile environments and strong CI/CD rely on a wealth of good quality testing and it’s one area where a lot of junior and mid developers are a bit short on. Testing is introduced but largely after the fact.Is the book worth your time?Yes, there is quality info to be had from the book. It makes an effort to give you whys over just a list of instructions without being overly fluffed-up to add book length where it was not required. Enjoyable read and the project was not an unpleasant build despite a few code errors in the book but they are easy enough to navigate around.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela