Redux Saga Tutorial | Redux setup in React components. | Part 3.

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.


React-redux Setup Example

Once we are done with the basic react setup. Moreover understanding of class-based, functional components, lifecycle and hooks. Although we have not covered the in-depth React in the tutorial as agenda here is to work with React Saga. So the last setup for working with React Saga is to finally set up our application with redux.


React redux we need to follow the following few strategies

  1. Create Redux global store.

  2. Create Redux reducers.

  3. Provide global store to react components.

  4. Connect component with the redux store.

  5. Add action creator and dispatch action from the component.

  6. Voila, we are done with the step of integrating redux with our Reactjs application.

Let's start with the process, although it's a simple process, I will explain it like you are doing it for the first time. If you are among anyone having a decent knowledge about the topic, just bear it with me for all those beginner folks.


Create Redux global store.

For creating a redux store we first need to define a store. For that, we will create a file with the name store.js in the root folder which will be having the code for the store.

// store.js

import {createStore, applyMiddleware, compose} from 'redux';
import reducers  from './reducer';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__  || compose;
export const store = createStore(reducers, composeEnhancers());

As told earlier, we are trying to create a store with the function named as createStore which we get from the redux library. We need to provide Reducer which we will be creating in the next part.


Create Redux reducers.

We create a redux reducer inside the folder named reducer. Let us start by creating two files named as index.js and home.js.

In the first index file, we will be putting the code for combining a couple of reducers. For simplicity, I am creating a single reducer here which will be named home.


// reducer/index.js

import {combineReducers} from 'redux';

import home from './home';

export default combineReducers({
    home
});

Let's create another file name as home.js which will be having our store and logic to update the value inside that store.


//reducer/home.js

const initialState = {
    title: 'This from store'
};

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

For now, I have written the case 'UPDATE_TITLE' directly here, but generally, we create a constant file where we keep our constant variables. After that, we can use it everywhere, just in case, we don't misspell it somewhere.


Till now we have created a Global store and our first reducer. Which has an initial state having a key as title, which we will update in the future using action creator.


Now is a good time to create our first action inside our folder action and then we create index.js in which we will be writing an action that will be updating our store based upon the condition written in the reducers.

These actions we will be using for dispatching from the component for performing any action.


// action/index.js

export const updateTitle = (payload) => {
    return {
        type: "UPDATE_TITLE",
        payload
    }
}

Now we are well through with setting up our react application and connecting it with a redux store.

So now our final step would be to call the action from any of the components either class-based or functional component. Following is the simple procedure for doing it.



//container/ClassBasedComponent.jsx

import React, { Component } from "react";
import { connect } from 'react-redux';
import { updateTitle } from '../action';

class ClassBasedComponent extends Component {
    constructor() {
        super();
        this.state = {
            name: "This is class"
        };
    }

    componentDidMount() {
        this.props.updateTitle("This is  from class based component.")
    }

    render() {
        const { title } = this.props;
        return (
            <>
                {title}
            </>
        )
    }
}

const mapDispatchToProps = {
    updateTitle
}

const mapStateToProps = function (state) {
    return {
        title: state.home.title,
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ClassBasedComponent);

We have used connect method, which uses the concept of currying in javascript, and for mapping the global store and action to the component, we create two functions called as mapStateToProps and mapDispatchToProps.

After these methods inside the props properly of our component, we have store and dispatch actions available. So we are in good shape to dispatch some action from our component which we have done inside componentdidMount.


We will see something like this on our screen, once we start our program using the following command.


> npm start









 

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.