I am trying to set a deeply nested object in my react.js/redux app via a reducer, but the object changes are not propagating down to my component. How should I update and mapStateToProps an object like this?
I have tried ...ing my action's payload in my reducer, mapping a higher level object in my mapStateToProps, and flattening the object I map to my components props.
My initial state:
const initialState = {
myObject : {
prop1 : {
prop2 : {
array1 : [],
array2: [],
array3: []
}
}
}
}
My reducer:
const app = (state = initialState, action) => {
switch(action.type) {
case SET_DATA:
return {
...state,
myObject: action.payload
};
} default:
return state;
}
export default app;
My Component:
class Component extends React.PureComponent() {
render() {
return (
{
JSON.stringify(this.props.componentObject)
}
);
}
}
function mapStateToProps(state) {
return {
componentObject: state.myObject
};
}
export default connect(mapStateToProps)(Component);
Action creator for updating nested object
export function setData(newDeeplyNestedObject) {
return {
type: SET_DATA,
payload: newDeeplyNestedObject
};
}
The result is that my Component is not displaying what is in Redux's state. It appears that the Redux is not detecting a change in my components props thus not updating the Component. Can anyone tell me how to make sure Redux sends updates to my component when a deeply nested object structure changes?
I know that Redux does a shallow compare for updates, but I feel like a JSON.parse(JSON.stringify()) in my reducer is not the right direction here.
mapStateToProps
is incorrect,myObject
is insidestate.app
but you are looking for it instate
. You need to do:componentObject: state.app.myObject
– Vaibhav Vishal