ReactJs adding multiple reducers with context

Viewed 334

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}}

1 Answers

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));

Related