React Redux – Multiple Reducer

We can have multiple reducer and combine them through rootReducer :
1. Create a store
2. Give a rootReducer to Store
3. rootReducer has two reducer

store.js

import * as redux from 'redux';

//Actions
export const COUNTER_INCREMENT = 'counter/increment';
export const COUNTER_DECREMENT = 'counter/decrement';

const initialState = {
  count: 0
}

const counterReducer = (state = initialState, action) => {
  switch(action.type){
    case COUNTER_INCREMENT : {
      return { ...state, count: state.count + 1};
      break;
    }
    case COUNTER_DECREMENT : {
      return { ...state, count: state.count - 1};
      break;
    }
    default: {
      return state;
    }
  }
}

const testReducer = (state = [], action) => {
  switch(action.type){
    case 'push' : {
      const data = [...state];
      data.push(action.value);
      return [...data]
      break;
    }
    case 'pop' : {
      const data = [...state];
      data.pop();
      return [...data];
      break;
    }
    default : {
      return state;
    }
  }
}

const rootReducer = (state = {}, action) => {
  return {
    counter : counterReducer(state.counter, action),
    tester: testReducer(state.tester, action)
  }
}
//There is another options to combine two reducer, it is called combineReducer in react.we pass these two reducer to that method

const store = redux.createStore(rootReducer);
export default store;

//Create a store
//Give a rootreducer to Store
//rootReducer has two reducer

index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import store, {COUNTER_INCREMENT, COUNTER_DECREMENT} from './store';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  increment = () => {
    store.dispatch({type: COUNTER_INCREMENT});
    console.log(store.getState().count)
  }

  decrement = () =>{
    store.dispatch({type: COUNTER_DECREMENT});
    console.log(store.getState().count);
  }

  push = () => {
    store.dispatch({type: 'push', value: Math.random()});
    console.log(store.getState())
  }

  pop = () =>{
    store.dispatch({type: 'pop', value: Math.random()});
    console.log(store.getState())
  }

  render() {
    return (
      <div>
        <Hello name={this.state.name} />
        <p>
          Start editing to see some magic happen :)
        </p>
        <button onClick={this.increment}>Increment</button>
        <button onClick={this.decrement}>Decrement</button>
        <button onClick={this.push}>Push</button>
        <button onClick={this.pop}>Pop</button>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Reference

Stackbliz

Leave a Reply

Your email address will not be published. Required fields are marked *