Pages

Subscribe:

Ads 468x60px

Monday, January 21, 2019

"React, Redux and Saga" Connecting the Dots.

"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 with number of years ;), and I’m quite fascinated about the UI work recently, since UI libraries are adopting some of the distributing computer theories/features used in middleware applications.

If you have worked with the 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 share 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 used the react, redux and saga. 

I will try to explain how the component interaction and state update works by using the sample I prepared for this post. The sample application uses react redux and saga. It is pretty straight forward, What it does is, it has a button which used to fetch all the users from executing a remote API call. See below diagram to simplify the concept behind the sample.


This is the simple workflow theory behind event dispatching, remote data fetching, state changes and propagate that 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 sample code that fire 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 all the users list. So we dispatch an event which is the type of ‘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.
When the ‘FETCH_USERS’ event got fired, there is a UserSaga, listening for this type of events, and it will fire up the UserApi.getUsers.(). After receiving the data, it will fire up another event to update the store. See 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. 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

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 into 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, 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. Hope you have gained some idea of how the component interaction works, 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
Or you can try to create the project from scratch. First, install the create-react-app using 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

Need to install the following react libraries.

npm install --save axios
npm install --save redux
npm install --save redux-saga
npm install --save react-redux 

No comments:

Post a Comment