Reputation: 2381
I have the following initial state for my react-redux
const initialState = {
logged: false,
user: null,
company: null,
}
When I first login, I set the state data
const data = action.payload.data;
const properties = action.payload.properties;
const notifications = action.payload.notifications;
return {
...state,
logged: true,
user: {
id: data.UserID,
firstName: data.UserFName,
lastName: data.UserLName,
email: data.UserEmail,
securityLevel: parseInt(data.SecurityLevelID),
notifications: {
multiProp: notifications.MultiProp && parseInt(notifications.MultiProp) === 1 ? false : true
}
},
company: {
id: data.CompanyID,
name: data.CompanyName,
email: data.ContactEmail,
leadSource: parseInt(data.LeadSourceCompanyID)
}
}
Then, at some point of my project, I need to update only user.notifications.multiProp
, so I created a new Type called UPDMULTIPROP and I'm doing:
case Types.UPDMULTIPROP:
const userData = action.payload.data;
return {
...state,
user: {
notifications: {
multiProp: userData.notifications.MultiProp && parseInt(userData.notifications.MultiProp) === 1 ? false : true,
}
}
}
However, it set all the other user state to undefined. How can I update just the multiProp
?
Thanks
Upvotes: 0
Views: 46
Reputation: 191
To update nested object immutably you need to spread it again. Like
user : { ...state.user, notifications : someValue }
Like this.
Upvotes: 1
Reputation: 388
user is also an object, to keep user state the same you should also spread the user.
case Types.UPDMULTIPROP:
const userData = action.payload.data;
return {
...state,
user: {
...state.user,
notifications: {
multiProp: userData.notifications.MultiProp && parseInt(userData.notifications.MultiProp) === 1 ? false : true,
}
}
}
Upvotes: 1