Redux Quick Start Guide
eBook - ePub

Redux Quick Start Guide

A beginner's guide to managing app state with Redux

James Lee, Tao Wei, Suresh Kumar Mukhiya

Condividi libro
  1. 204 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Redux Quick Start Guide

A beginner's guide to managing app state with Redux

James Lee, Tao Wei, Suresh Kumar Mukhiya

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Integrate Redux with React and other front-end JavaScript frameworks efficiently and manage application states effectively

Key Features

  • Get better at building web applications with state management using Redux
  • Learn the fundamentals of Redux to structure your app more efficiently
  • This guide will teach you develop complex apps that would be easier to maintain

Book Description

Starting with a detailed overview of Redux, we will follow the test-driven development (TDD) approach to develop single-page applications. We will set up JEST for testing and use JEST to test React, Redux, Redux-Sage, Reducers, and other components. We will then add important middleware and set up immutableJS in our application. We will use common data structures such as Map, List, Set, and OrderedList from the immutableJS framework. We will then add user interfaces using ReactJS, Redux-Form, and Ant Design.

We will explore the use of react-router-dom and its functions. We will create a list of routes that we will need in order to create our application, and explore routing on the server site and create the required routes for our application. We will then debug our application and integrate Redux Dev tools.

We will then set up our API server and create the API required for our application. We will dive into a modern approach to structuring our server site components in terms of Model, Controller, Helper functions, and utilities functions. We will explore the use of NodeJS with Express to build the REST API components. Finally, we will venture into the possibilities of extending the application for further research, including deployment and optimization.

What you will learn

  • Follow the test-driven development (TDD) approach to develop a single-page application
  • Add important middleware, such as Redux store middleware, redux-saga middleware, and language middleware, to your application
  • Understand how to use immutableJS in your application
  • Build interactive components using ReactJS
  • Configure react-router-redux and explore the differences between react-router-dom and react-router-redux
  • Use Redux Dev tools to debug your application
  • Set up our API server and create the API required for our application

Who this book is for

This book is meant for JavaScript developers interesting in learning state management and building easy to maintain web applications.

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Redux Quick Start Guide è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Redux Quick Start Guide di James Lee, Tao Wei, Suresh Kumar Mukhiya in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in JavaScript. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2019
ISBN
9781789806342

Extending Redux with Middleware

In this chapter, we are going to learn about what middleware is, look at different types of middleware, and learn about how they work. We are also going to extend our Redux store using the Saga middleware. We covered the concept of router middleware in Chapter 3, Routing.
In this chapter, we will cover the following topics:
  • Learning about middleware and its related patterns
  • Exploring the usage of redux-saga as middleware
  • Outlining some further reading resources

Exploring middleware

Middleware is some code that we can use between the framework that is receiving a request, and the framework that is generating a response. Generally, middleware presents a third-party extension point in dispatching an action, and the moment it reaches the reducer. We covered the concepts of actions and reducers in Chapter 1, Understanding Redux. Do you remember it? Developers apply the Redux middleware for logging, communicating with an asynchronous API, crash reporting, language translation, handling side effects, and routing.
We will continue with the code base we have in Chapter 5, React with Redux, and add more functionalities on top of it. In this chapter, we are going to extend the store with some middleware.

Router middleware

We have already used the connected-react-router/immutable library in Chapter 3, Routing, in which we implemented routerMiddleware to solve the routing issue. To recap, we are using this library as the binding for React Router V4. We extended our store using this middleware when we configured the store. The code snippet can be found in the app/configureStore.js file in both CH03 and CHO5.

redux-saga middleware

redux-saga is a third-party JavaScript library that helps to easily and efficiently manage an application's side effects, including asynchronous activities such as fetching data and accessing browser cache.
Mukhiya and Hung outline the essential importance of using redux-saga in a web application. We can use the image used in this paper as a reference to better understand the need for redux-saga. To explain it in one sentence, we can say that redux-saga is responsible for handling side effects. Saga uses ES6 Generators (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*) to make asynchronous flows easy to read, write, and test. If you are not familiar with generators, it would be best to pause before the next section and read up on them. Here is a couple of suggested articles: https://redux-saga.js.org/docs/ExternalResources.html.
Basically, generators are functions that provide the flexibility to be paused and resumed rather than executing all the statements in one pass. yield in a generator represents an asynchronous step in a more synchronous process, and is analogous to await in an async function:
Figure 6.1: The logical model of the single page architecture using Redux-Saga [1]
Redux Saga provides us with the async dispatch which ensures HTTP requests will not clutter up the execution flow. Redux Saga creates all the logic of event stream processing. Saga runs in the background right after the app is launched and observes all the actions that the store dispatches. Once it finds that the correct actions have been dispatched, it listens to them and performs any necessary asynchronous activities, such as fetching data or deleting data from the backend by calling the API layer. For example, in the preceding diagram, once Saga observes that the DELETE action been dispatched, it will call the API with the correct payload to delete the doctor. The reducers take in the types of the actions and update the store's data, which in turn are reflected in the actional DOM [1].

Getting started

We are going to extend the application that we worked on in Chapter 5, React with Redux. We will be fetching data from a real REST API using the Redux Saga middleware. To get started, the first step is to add the library to our application.

Adding Saga to the application

From inside the application root, we can add Saga as follows:
yarn add redux-saga
OR
npm install --save redux-saga
While the library can be used directly in containers to pass in a higher-order function, we are going to use Saga as middleware. Later, we will be discussing the benefits of having it as middleware.
In order to run Saga, we require two things:
  • A Saga middleware with a list of Saga functions
  • We need to connect middleware to the Redux store

Connecting the Saga middleware to the store

We can add Saga to our middleware using the following snippet. We can modify the configureStore.js file inside app/configureStore.js as follows:
import { createStore, applyMiddleware, compose } from 'redux';
import { fromJS } from 'immutable';
import { routerMiddleware } from 'connected-react-router/immutable';
import createSagaMiddleware from 'redux-saga';

import createReducer from './reducers';

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history) {
const middlewares = [sagaMiddleware, routerMiddleware(history)];

const enhancers = [applyMiddleware(...middlewares)];

const store = createStore(
createReducer(),
fromJS(initialState),
compose(...enhancers),
);

// Extensions
store.runSaga = sagaMiddleware.run;
store.injectedReducers = {};
store.injectedSagas = {};

return store;
}
The most notable points are as follows:
  • We are using the createSagaMiddleware factory function from redux-saga. To find out more about factory functions, consider reading the documentation website (https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html).
  • We create the Saga middleware and pass it to the store.
To understand the concept of redux-saga, we will take the help of the pre-built REST API. We will discuss more about how these REST APIs are built in Chapter 8, Understanding the REST API. Without going more detail about how the REST API is constructed using Express and Node.js, we assume that we have an API that provides authentication and authorization and other required endpoints. W...

Indice dei contenuti