Redux excels at not only global state, but complex global state. Today, we’ll be using multiple reducers to manage separate parts of the store
Combined reducers is nothing more than pulling in more than one reducer from source and creating a keyed object from them.
import todoReducer from './todo.store.js';
import itemReducer from './item.store.js';
let reducers = combineReducers({
todo: todoReducer,
item: itemReducer,
});
Once done, any component can reach into the store and get either one, both, or all …
import * as actions from "../../store/todo.store.js";
import * as itemActions from "../../store/item.store.js";
const mapStateToProps = state => ({
todo: state.todo,
item: state.item,
});
const mapDispatchToProps = (dispatch, getState) => ({
deleteItem: id => dispatch(actions.deleteItem(id)),
hideDetails: id => dispatch(itemActions.hideDetails()),
});
What’s the point?
Each reducer really should have only 1 part of state to manage
// YES:
const initialState = { value: 0 };
// NO:
const initialState = { value: 0, numChanges:0, changes:[] };
// Move those to separate reducers/actions
What about the actions?
//counter.store.js
export default function reducer (state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { value: state.value + 1 }
case 'RESET':
return {value:0};
default:
return state;
}
}
//history.store.js
export default function reducer (state = initialState, action) {
switch (action.type) {
case 'CLICK':
return { clicks: state.clicks + 1 }
case 'RESET':
return {clicks:0};
default:
return state;
}
}