AbhayVel / manishReact

Apache License 2.0
1 stars 0 forks source link

Explain Basic of Redux with nodeJs. #1

Open Amrutaquickitdotnet opened 2 years ago

Amrutaquickitdotnet commented 2 years ago

Please install following Packages to use redux.

  1. "@reduxjs/toolkit": "1.8.5",
  2. "react-redux": "8.0.2"

Redux is all about one central store for all data. we never have multiple stores in redux. We can store any data in it. we store data in the Redux store with help of Reducer. Also, we subscribe to the data change. Basic redux has 6 main components.

  1. Store
  2. Reducer
  3. subscriber
  4. dispatch
  5. Action To use redux , we need to import redux. const redux = require('redux');

Store=> Then we need to create a store which require Reducer(callback method) as input. Reducer=> Reducer accept two parameters one is state and second is action. It always return state**. subscriber**=> To track changes in state we use subscriber so it is possible to subscribe from any file any time. `const actionSubscriber = () => { var data = store.getState(); console.log(data); }

store.subscribe(actionSubscriber);`

dispatch => dispatch help to change state. store.dispatch({ type: 'login', payload: { userName: "abhay", role: "admin" } });

const redux = require('redux');
const initialValue = {
    isLogin: false,
    userName: "",
    role: ""
}
const myReducer = (state = initialValue,action) => {

    if (action.type == 'login') {
        return {
            isLogin: true,
            userName: action.payload.userName,
            role: action.payload.role
        }
    }
    if (action.type == 'logout') {
        return {
            isLogin: false,
            userName: "",
            role: ""
        }
    }
    return state;
}
const store = redux.createStore(myReducer)

const actionSubscriber = () => {
    var data = store.getState();
    console.log(data);
}

store.subscribe(actionSubscriber);

store.dispatch({ type: 'login', payload: { userName: "abhay", role: "admin" } });
store.dispatch({ type: 'logout' });
store.dispatch({ type: 'login', payload: { userName: "xx", role: "admin" } });

image

Amrutaquickitdotnet commented 2 years ago

You can see code for this in following path $/demo2\reactwithnodeJs/canrun.js