Day 2 - Redux Project Setup and Store and Action in Redux
Categories - Redux Tags - Redux React Js JavaScript   Maniruzzaman Akash   3 weeks ago   42   0

Day 2 - Redux Project Setup and Store and Action in Redux

Welcome to our Redux JS course. 

Today, we'll do the following parts

  1. Install a node JS project
  2. Install Redux
  3. Learn some basic concept of Redux using practical example.

 

Create a Node JS project:

npm init

And continue with npm with all of the default values.

 

Install ReduxJS toolkit:

npm install @reduxjs/toolkit

We've installed @reduxjs/toolkit in our project using this command. This package actually uses some of the core redux libraries. You can check this link of Redux JS official documentation -  https://redux.js.org/introduction/getting-started

 

Check Full Package.json

Check our full package.json would be something like this - 

{
  "name": "redux-start",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "type": "module",
  "license": "ISC",
  "dependencies": {
    "@reduxjs/toolkit": "^1.6.1"
  }
}

 

Look, we've added aditional "type": "module",  so that we could work with ES6. You could make your setup something like this. Later you could change everything as you want. But, for now, just continue as like this.

 

Add index.js:

As, we've seen in package.json, we've added index.js as our main runnable file. So just create an index.js file. Let's check our index.js works or not, by writting this one line - 

console.log("Hello");

 

Run Project:

as we don't setup any watcher or nodemon, for now, we'll check changes inside the index.js file using as a node application. Using the command in terminal - 

node index.js

You could see, the Hello in the console. Great.

 

Work with Redux:

So, we've setup all of our environment. Now let's work with redux.

 

Create a Redux Store:

So, we already discuss previously, Redux will implement the single source of truth pattern, so we need a central store for our Redux application. This store will be managed by our entire application. Every values we need, we'll add in this store or delete from this store. So, let's create a store - inside our index.js file:

import { createStore } from 'redux'

Ok, to create an actual store we need another thing - Reducer.

 

What is Reducer:

We could say from the documentation - 

Reducer is a function that takes a current state value and an action object describing "what happened", and returns a new state value.

A reducer's function signature is: (state, action) => newState

So, reducer actually do these things - 

  1. Takes current state value as input
  2. Returns new state value as output.

 

Let's create a CounterReducer

const initialState = { 
   value: 0
}

/**
* CounterReducer
*
* Takes initialState inside state
* Send an action in second parameter
*/
function CounterReducer(state = initialState, action) {
  switch (action.type) {

    // If 'INCREMENT_ONE' event happen:
    case "INCREMENT_ONE":
      return {
        value: state.value + 1,
      };

    // If 'DECREMENT_ONE' event happen:
    case "DECREMENT_ONE":
      return {
        value: state.value - 1,
      };

    // By deault, if nothing happens return the old state.
    default:
      return state
  }
}

 

So, at first inside our CounterReducer, first initial state is this - 

const initialState = { 
   value: 0
}

Where value = 0, we could asume it like counter value. Then inside Reducer function, we've taken that initialState as input also an action.

Based on that action type, we do some thing to our state. We then update the state and return.

Like, if INCREMENT_ONE action type happens, we do this thing - 

// If 'INCREMENT_ONE' event happen:
case "INCREMENT_ONE":
   return {
      value: state.value + 1,
   };

We just update the previous state value to  increase 1 and return that object as new object.

Same is for Decrement - 

    // If 'DECREMENT_ONE' event happen:
    case "DECREMENT_ONE":
      return {
        value: state.value - 1,
      };

 

So, complete our complete our store object with this reducer. 

let store = createStore(CounterReducer);

 

Then any event happen to this store, we can listen very easily - store.getState()

console.log("store state", store.getState());

Then we could see the default object inside our CounterReducer store.

 

Change In Redux Store Data: dispatch()

store.dispatch({ type: "INCREMENT_ONE" });
console.log("store state after", store.getState());

dispatch() is the function where action type is passed and which is processed in CounterReducer. So, when INCREMENT_ONE dispatches it would increment the value to one and return the new state. We could also see the console if we run using `node index`. We'll see - 

{
    value: 1
}

 

So, to decrement one same as this - 

store.dispatch({ type: "DECREMENT_ONE" });
console.log("store state after dec", store.getState());

It will be now, same as previous value of counter.

{
    value: 0 // decremented value
}

 

So, final index.js file would be - 

console.log("Hello");

import { createStore } from "redux";

const initialState = {
  value: 0,
};

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case "INCREMENT_ONE":
      return {
        value: state.value + 1,
      };

    case "DECREMENT_ONE":
      return {
        value: state.value - 1,
      };
    default:
      return state;
  }
}

let store = createStore(counterReducer);

console.log("store state", store.getState());

store.dispatch({ type: "INCREMENT_ONE" });
console.log("store state after", store.getState());

store.dispatch({ type: "DECREMENT_ONE" });
console.log("store state after dec", store.getState());

Run node index.js

To detect real change - do increment_one three times - 

store.dispatch({ type: "INCREMENT_ONE" });
store.dispatch({ type: "INCREMENT_ONE" });
store.dispatch({ type: "INCREMENT_ONE" });
console.log("store state after", store.getState());

Now state value would be - 

{
    value: 3
}

 

That's It. Hope, you've got a basic concept of Redux -

 

Github Code Link - https://github.com/ManiruzzamanAkash/redux-learning/tree/Day2

Video Tutorial of Redux Day 2:

 

Previous
Redux JS Introduction - What, Why and How to start