Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

React, Redux and Saga: Connecting the Dots

DZone 's Guide to

React, Redux and Saga: Connecting the Dots

We look at how to implement microservices architectural patterns on the front-end using React, Redux, and the saga pattern.

Free Resource

"Viewer discretion advised." This article is written by a person who is very new to front-end programming with React and worked on backend development for a number of years. I’m quite fascinated, however, by UI recently, since UI libraries are adopting some of the distributed computing theories/features used in middleware applications.

If you have worked with Angular, passing state within components is not as clean as you would have liked. In my personal opinion, React handled the situation quite delicately using React-Redux, a centralized big static state object, which was shared within the whole application, and react-saga, a library which handles the application side effects, e.g. asynchronous actions. In this tutorial, we will build a React application which uses the Redux and the saga pattern. 

I will try to explain how the component interaction and state update works by using the sample I prepared for this post. The sample app is pretty straight forward. It has a button which fetches all the users by executing a remote API call. See the below diagram for a visualization:

This is the simple workflow theory behind event dispatching, remote data fetching, state changes, and propagating those changes to the UI. This cycle continues until the lifecycle of the component ends.

A. Denotes the UI action which resulted in a dispatch event. Below is some sample code that fires up a dispatch event with the event name and the data used for the event. In this example, we dispatch a UI event to fetch the users list. So we dispatch an event of type FETCH_USERS.

const mapDispatchToProps = (dispatch) => {
    return {
        fetchUsers : () => {
            dispatch({
                type: 'FETCH_USERS'
            })
        }};};

B. We have an API call defined to get all user data, from a mockable URL: http://demo7507024.mockable.io/react-sample. When the FETCH_USERS event got fired, there was a user saga listening for this type of event, and it fired up the  UserApi.getUsers() method. After receiving the data, it fired up another event to update the store. See the below code snippet in the UserSaga.js file:

//Fetching the users list
const response = yield call(UserApi.getUsers);

// Then instructing the middleware to action to update the store.
        yield put({
            type: ACTION_TYPES.UI_ACTION.ON_USERS_DATA,
            data: response.data
        });

In UserSaga.js, we have defined the takeEvery(pattern, saga, ...args), so whenever it matches the ‘FETCH_USERS’ pattern, it will dispatch the event, to update the store. With each call it will construct a new task for the matching event.

An application can have multiple sagas’s based on the requirement, so we pile them into one main saga, as in the MainSaga.js file.

C. Now comes to the store update section, as you saw on the step ‘B’ there is a new event fired to update the redux store, which is ‘ON_USERS_DATA’, so we have to catch that event and update the state change. For that we used the UserReducer.js

export default function userReducer(state = initialState, action) {
    switch (action.type) {
        case ACTION_TYPES.UI_ACTION.ON_USERS_DATA:
            return Object.assign({}, state, {userList: action.data});
        default:
            return state;
    }
}

Here we have updated the userList in the store object with the new data. Now the update of the Redux store is complete.

D. Now we have to listen to that state update and handle the UI update in the render method, inside the component. We will receive the update to the component via the mapStateToProps method.

const mapStateToProps = (state) => {
    return {
        users: state.userActions.userList
    };
};

Now, the newly fetched user list is visible to the UI. So now you have connected the dots between React, Redux, and redux-saga. I hope you have gained some idea of how the component interactions work and don’t forget to comment on your thoughts as well.

Source code for this sample can be found here. https://github.com/arunasujith/react-redux-saga-sample. You can also try to create the project from scratch. First, install the create-react-app using he below command.

npm i -g create-react-app

Now create a sample project.

create-react-app react-redux-saga-sample

Run the project using:

npm start

Commands to install the various React libraries.

npm install --save axios
npm install --save redux
npm install --save redux-saga
npm install --save react-redux
Topics:
microservices ,saga pattern ,react tutorial ,redux ,microservices tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}