Remember the first principle of Redux: all app state is held in a single state object in the store. You define multiple reducers to handle different pieces of your application's state, then compose these reducers together into one root reducer.
The root reducer is then passed into the Redux createStore() method.
Redux gives us the combineReducers() method. Which accepts an object as an argument in which you define properties and give them keys to specific reducer functions.
For the example coming up the state held in the Redux store would be a single object containing count and auth properties.
Code:
constINCREMENT='INCREMENT';constDECREMENT='DECREMENT';constcounterReducer=(state=0,action)=>{switch(action.type){caseINCREMENT:returnstate+1;caseDECREMENT:returnstate-1;default:returnstate;}};constLOGIN='LOGIN';constLOGOUT='LOGOUT';constauthReducer=(state={authenticated:false},action)=>{switch(action.type){caseLOGIN:return{authenticated:true}caseLOGOUT:return{authenticated:false}default:returnstate;}};constrootReducer=// Define the root reducer hereconststore=Redux.createStore(rootReducer);
With the counterReducer() and authReducer() functions provided to us along with the Redux store. Let's finish writing the rootReducer() function using the Redux.combineReducers() method. Then we have to give counterReducer and authReducer a key.
Top comments (0)