Redux Saga Tutorial | Implement redux-saga with ReactJS and Redux.| Part 4

A Complete Guide To Redux-Saga With React JS and Redux project.


Following is the overview of what we are planning to discuss in this article. So we will discuss a few of the following topics in the article in chronological order. This will be a 4 part series containing the information about React Saga.

React Tutorial Overview article.


Redux Saga Setup

So till now, we are done with setting up the react-redux with class-based and functional components. Also, we have discussed the react js lifecycle methods and their implementation using the hooks.

If you still wondering about the basic react js logic which you need to understand I will highly recommend you to go through parts 1-3 of this 4 part series. This is the last part of the tutorial in which we will cover the react saga setup.


Let's first divide the entire process into some substeps.

  1. Add React-Saga listener.

  2. Adding a saga file for the actual logic.

  3. Adding conditions in the reducer for updating the store.

Add React-Saga listener.

The next obvious step is to install react saga, which can be done using the following command

> npm install react-saga

This will add react saga module into your node modules, which now we can add to our middleware. A listener will be set up which will intercept the request so that we can perform further actions.


// src/store.js

import {createStore, applyMiddleware, compose} from 'redux';
import reducers  from './reducer';
import createSagaMiddleware from 'redux-saga'
import mySaga from './sagas';

// create the saga middleware
const sagaMiddleware = createSagaMiddleware()

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__  || compose;

// mount it on the Store
export const store = createStore(reducers, composeEnhancers(applyMiddleware(sagaMiddleware)));

// then run the saga
sagaMiddleware.run(mySaga)

Here we have added a couple of lines in our store.js file. Basically included sagaMiddleware into the store and along with we have started sagaMiddleware with the run command. The run command requires our saga file which will have all the logic about the saga.

The next obvious step would be to create our saga logic, although these steps are not in any chronological order, our entire saga logic will only work once we are done with all the code.


Adding a saga file for the actual logic.

Next step is to setup our saga logic, which we keep inside the 'saga' folder.

We can create a folder named sagas, which will have all the files and saga logic written.

Here we have imported takeLatest and takeEvery from redux-saga, these help us intercept the request that is dispatched by the action creator.


// src/sagas/index.js

import {
    call,
    put,
    takeEvery,
    takeLatest
} from 'redux-saga/effects'
import { UPDATE_TITLE, UPDATE_TITLE_FROM_SAGA } from '../constants';

// worker Saga: will be fired on USER_FETCH_REQUESTED actions
function* updateTitle(action) {
    try {
        yield put({ type: UPDATE_TITLE_FROM_SAGA, payload: `${action.payload}-Sagas` });
    } catch (e) {
        console.log(e);
    }
}

function* mySaga() {
    yield takeLatest(UPDATE_TITLE, updateTitle);
}

export default mySaga;

At the last of the file, we have a takeLatest method from react saga, which is listening to UPDATE_TITLE. The takeLatest means if we dispatch the action with UPDATE_TITLE multiple times, we will only listen to the latest one.


This takeLatest and takeAny comes very handily I will recommend learning about them a bit more. So once we encounter UPDATE_TITLE we will call the function updateTitle.


Here in the updateTitle we haven't done much, for now, just dispatched another action using the put method provided by redux-saga, which will update the reducer against the case UPDATE_TITLE_FROM_SAGA.


Finally, let's write the logic to update the reducer which will help us understand the final logic.


Adding conditions in the reducer for updating the store.

Here inside our reducer, we will add another condition i.e. UPDATE_TITLE_FROM_SAGA which will be dispatched by our function which we have written in the saga file.


import {
    UPDATE_TITLE_FROM_SAGA} from '../constants';
const initialState = {
    title: 'This from store'
};

export default function home(state = initialState, { type, payload }) {
    switch (type) {
        // case UPDATE_TITLE:
        //     return {
        //         ...state,
        //         title: payload
        //     }

        case UPDATE_TITLE_FROM_SAGA:
            return {
                ...state,
                title: payload
            }
        default:
            return state;
    }

}

Once we have updated the logic inside the reducer it will show us that the store is been updated by the action which we have dispatched from our saga method. Inside our saga, we write a generator function that helps you return the result at various stages.

Although in this example we haven't called any API you can also call any API call.


Once you start your program now, you will see the following screen, of course, if everything is done right.


 

Here you can find the link for all the parts.

Important Links:


 
Video Tutorial Link

A video tutorial explaining the above concept.





 
Github Source Code

Source Code Link: https://github.com/apoorvtomar2222/redux-saga-tutorial

 

About The Author Apoorv Tomar is a Software developer and part of Mindroast. You can connect with him on Twitter, Linkedin, Telegram and Instagram. Subscribe to the newsletter for the latest curated content. Don’t hesitate to say ‘Hi’ on any platform, just stating a reference of where did you find my profile.

apoorv-pic.jpg

Hi, thanks for stopping by!

Hope you are getting benefitted out of these articles. Don't forget to subscribe to the Newsletter where we will serve you with the curated content right at your mailbox.

Let the posts
come to you.

Sponsor the Author.