I am not sure how to update the state
properly in redux
. I get duplicated entries.
Thats how the state
looks like
const STATE = {
windowOne: { ... }
windwoTwo: { ... }
windowThree: { ... }
}
That is one of my reducers
export default function reducer(state = STATE, action) {
switch (action.type) {
case type.WINDOW_ONE: {
return {
...state,
windowOne: {
...state.windowOne,
foo: action.bar,
}
}
}
}
}
I map the state like to the props of my component
function mapDispatchToProps(dispatch) {
return bindActionCreators(combinedActions, dispatch);
}
const mapStateToProps = state => {
const { windowOne } = state.windowOne;
return {
windowOne,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent);
And I combine the various reducers here
export default combineReducers({
windowOne,
windowTwo,
windowThree
});
When I use redux-logger
, I see that in windowOne
the whole state
is copied. In there, after triggering an action
, I find windowTwo
and windowThree
. I am also not sure why I have to specify windowOne
in these lines
const { windowOne } = state.windowOne;
Shouldn't const { windowOne } = state
be enough? That might be related...
Check the docs for combineReducers
; it takes care of sending to each reducer the appropriate slice of the state and merging the results. For the reducer shown, this means you should pass it the initial state for windowOne
only and return just the updated state for windowOne
:
export default function reducer(state = STATE.windowOne, action) {
switch (action.type) {
case type.WINDOW_ONE: {
return {
...state,
foo: action.bar,
}
}
}
}
After this, const { windowOne } = state
in mapStateToProps
should work. Also note that you'll need a default case in each reducer, as all reducers receive all actions, and that STATE
might be more appropriately named initialState
.