Hands-On Full-Stack Web Development with GraphQL and React
eBook - ePub

Hands-On Full-Stack Web Development with GraphQL and React

Build scalable full-stack applications while learning to solve complex problems with GraphQL

Sebastian Grebe

Share book
  1. 468 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Hands-On Full-Stack Web Development with GraphQL and React

Build scalable full-stack applications while learning to solve complex problems with GraphQL

Sebastian Grebe

Book details
Book preview
Table of contents
Citations

About This Book

Unearth the power of GraphQL, React, Apollo, Node, and Express to build a scalable, production ready application

Key Features

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

Book Description

React, one of the most widely used JavaScript frameworks, allows developers to build fast and scalable front end applications for any use case. GraphQL is the modern way of querying an API. It represents an alternative to REST and is the next evolution in web development. Combining these two revolutionary technologies will give you a future-proof and scalable stack you can start building your business around.

This book will guide you in implementing applications by using React, Apollo, Node.js and SQL. We'll focus on solving complex problems with GraphQL, such as abstracting multi-table database architectures and handling image uploads. Our client, and server will be powered by Apollo. Finally we will go ahead and build a complete Graphbook. While building the app, we'll cover the tricky parts of connecting React to the back end, and maintaining and synchronizing state. We'll learn all about querying data and authenticating users. We'll write test cases to verify the front end and back end functionality for our application and cover deployment. By the end of the book, you will be proficient in using GraphQL and React for your full-stack development requirements.

What you will learn

  • Resolve data from multi-table database and system architectures
  • Build a GraphQL API by implementing models and schemas with Apollo and Sequelize
  • Set up an Apollo Client and build front end components using React
  • Use Mocha to test your full-stack application
  • Write complex React components and share data across them
  • Deploy your application using Docker

Who this book is for

The book is for web developers who want to enhance their skills and build complete full stack applications using industry standards. Familiarity with JavaScript, React, and GraphQL is expected to get the most from this book.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Hands-On Full-Stack Web Development with GraphQL and React an online PDF/ePUB?
Yes, you can access Hands-On Full-Stack Web Development with GraphQL and React by Sebastian Grebe in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in JavaScript. We have over one million books available in our catalogue for you to explore.

Information

Year
2019
ISBN
9781789135763
Edition
1

Reusable React Components

We have done a lot to reach this point in the book, including saving, requesting, inserting, and updating data through the use of Apollo Client, in connection with our GraphQL API. Much of the code that we have written will also have to be reviewed many times. This is especially important because we are building an application so quickly. Everything is working for now, but we have not done a great job here; there are some best practices and tactics that need to be observed in order to write good React applications.
This chapter will cover everything you need to know in order to write efficient and reusable React components. It will cover the following topics:
  • React patterns
  • Structured React components
  • Rendering nested components
  • The React Context API
  • The Apollo Consumer component

Introducing React patterns

With any programming language, framework, or library that you use, there are always common tactics that you should follow. They present an understandable, efficient way to write applications.
In Chapter 4, Integrating React into the Back end with Apollo, we tackled some patterns, such as rendering arrays, the spread operator, destructuring objects, and higher-order components. Nevertheless, there are some further patterns that you should know about.
We will go over the most commonly used patterns that React offers, as follows:
  • Controlled components
  • Stateless functions
  • Conditional rendering
  • Rendering children
Many (but not all) of the examples here only represent illustrations of what each method looks like. Some of them will not be taken over to our real application code, so, if you are not interested in learning the essential aspects of patterns, or if you already know most of them, you can skip the examples.
Beyond the short explanation that I will provide, there is more extensive documentation on this topic. The official React documentation is always a good starting point, but you can find all React patterns, including those that we have already used, at https://reactpatterns.com/.

Controlled components

When we wrote our post form to submit new posts or the message inputs inside chat in the previous chapters, we used controlled input by incident. To provide a better understanding, I am going to quickly explain the difference between controlled and uncontrolled components, and when to use each of them.
Let's start with uncontrolled input.
By definition, a component is uncontrolled whenever the value is not set by a property through React, but only saved and taken from the real browser DOM. The value of an input is then retrieved from a reference to the DOM Node, and is not managed and taken from React's component state.
The following code shows the post form where the user will be able to submit new posts. I have excluded the rendering logic for the complete feed, as it is not a part of the pattern that I want to show you:
import React, { Component } from 'react';
import gql from 'graphql-tag';
import { Mutation } from 'react-apollo';

const ADD_POST = gql`
mutation addPost($post : PostInput!) {
addPost(post : $post) {
id
text
user {
username
avatar
}
}
}`;

export default class Feed extends Component {
constructor(props) {
super(props);
this.textArea = React.createRef();
}
render() {
const self = this;
return (
<div className="container">
<div className="postForm">
<Mutation mutation={ADD_POST}>
{addPost => (
<form onSubmit={e => {
e.preventDefault();
addPost({ variables: { post: { text:
self.textArea.current.value } } });
}}>
<textarea ref={this.textArea} placeholder="Write your
custom post!"/>
<input type="submit" value="Submit" />
</form>
)}
</Mutation>
</div>
</div>
)
}
}
In this example, you can see that we no longer have a state initializer, since the textarea value is stored within the real DOM Node, and not the application state.
Now, we need a component constructor. As we stated in Chapter 1, Preparing Your Development Environment, you always need to run the super method inside of a constructor first.
Next, we run the createRef function provided by React. It prepares the variable to accept the DOM Node as a property. In earlier versions of React, you were required to use a callback to handle this on your own. From version 16.3 of React, the createRef function automates this process for you.
In the render method, the ref property fills in the reference that we just created with the DOM element.
Accessing the value of the DOM Node works by using the normal JavaScript DOM API. You can see this behavior when sending the submit event of our form. The value is extracted from the self.textArea.current.value field.
Everything that an uncontrolled component needs is already shown here; there is no more to it. You can compare this approach to our current implementation of the post form. In our implementation, we set up the state, listen for change events, and save and read the value directly from the component state, not from the DOM element.
When using uncontrolled components and working directly with DOM elements, the problem is that you leave the normal React workflow. You are no longer able to handle conditions and, therefore, trigger other events inside of React.
Nevertheless, the DOM reference can make it easier to use third-party plugins that were not written for the React ecosystem. There are thousands of great jQuery plugins, for example. I always recommend using the default approach of a controlled component. For 99% of cases, this works without leaving the React workflow.
If you need a deeper understanding of which approach is a better solution for your specific case, take a look at https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/.

Stateless functions

One fundamental and efficient solution for writing well-structured and reusable React components is the use of stateless functions.
As you might expect, stateless functions are functions, not React components. They are not able to store any states; only properties can be used to pass and render data. Property updates are directly rerendered inside of the stateless functions, and cannot be handled by the componentWillReceiveProps method, as in React components.
We have written a lot of code where stateless functions can be used very easily; while doing so, we have also structured and improved the readability of our React application.
Beginning with the file structure, we will create a new folder for our new components (or stateless functions), as follows:
mkdir src/client/components
Many parts of our application need to be reworked. Create a new file for our first stateless function, as follows:
touch src/client/components/loading.js
Currently, we display a dull and boring Loading... message when our GraphQL requests are running. Let's change this by inserting the following code into the loading.js file:
import React from 'react';

export default ({color, size}) => {
var style = {
backgroundColor: '#6ca6fd',
width: 40,
height: 40,
};

if(typeof color !== typeof undefined) {
style.color = color;
}
if(typeof size !== typeof undefined) {
style.width = size;
style.height = size;
}

return <div className="bouncer" style={style}></div>
}
In the preceding code, we are using a simple function in ES6 arrow notation. It is an easy and more concise syntax for defining functions. In the code, you can see that we are extracting the color and size fields from the...

Table of contents