2

I have implemented single reducer but I want to add multiple reducers here ? I searched to get solution but i am still stuck here

 1 - loginReducer.js
    export const loginReducer = (state, action) => {
        switch (action.type) {
          case 'LOGIN':
            return [
              ...state,
              {
                loggedIn: true,
              }
            ];
          case 'LOGOUT':
            loggedIn: false,

            return state ;
          default:
            return state;
        }
      };

2 - provider.js

import { loginReducer } from "./reducers/loginReducer";

const GlobalContext = React.createContext();
const GlobalProvider = props => {
  const [login, dispatch] = useReducer(loginReducer, []);
  return(
    <GlobalContext.Provider value={{login, dispatch}}> 
      {props.children}
    </GlobalContext.Provider>
  )
}

export default GlobalProvider;

How can I add another reducer same like loginReducer ?

and What is the syntax to add here GlobalContext.Provider value={{login, dispatch}}

ShibinRagh
  • 6,530
  • 4
  • 35
  • 57

1 Answers1

1

You can use Array.prototype.reduce:

const reducerA = (state, action) => state + action;
const reducerB = (state, action) => state * action;
const rootReducer = (state, action) =>
  [reducerA, reducerB].reduce(
    (state, reducer) => reducer(state, action),
    state
  );
console.log('root reducer:',rootReducer(1, 2));
HMR
  • 37,593
  • 24
  • 91
  • 160
  • Its working fine but when I console not getting initial state data from reducerB @HMR – ShibinRagh Jun 07 '20 at 17:30
  • @ShibinRagh That may be because you get the initial state from reducerA, when reducerB is called the first time it gets the result of reducerA. Maybe what you are looking for instead is your own version of [combineReducers](https://redux.js.org/api/combinereducers#combinereducersreducers)? – HMR Jun 07 '20 at 18:29