Redux - Setting Up Reducer and Store

From Logic Wiki
Jump to: navigation, search


Installation

npm i --save redux

Usage

Create a file in root called redux-basics.js and in this file we'll create Store, Reducer, Dispatching Action and Subsription. to run this file

node redux-basics.js
const redux = require('redux')  // Node.js syntax of importing 
const createStore = redux.createStore;
const initialState ={
counter:0
}
// Reducer
const rootReducer = (state = initialState, action) => {
  if (action.type === 'INC_COUNTER'){
    return {
      ...state,
      counter:state.counter + 1
     };
  }
  if (action.type === 'ADD_COUNTER'){
    return {
      ...state,
      counter:state.counter + action.value
     };
  }
  return state;
};
//Store
const store = createStore(rootReducer);
console.log(store.getState());

// Subsription
  store.subscribe(()=> {
    console.log('Subscription', store.getState());
  });

// Dispatching Action
store.dispatch({type: 'INC_COUNTER'});
store.dispatch({type: 'ADD_COUNTER', value:10});
console.log(store.getState()); 

subscription triggered whenever the state is updated.