I am using React and Redux and i need to update my state with updated data. My state contains an array of objects like this:
[
{
"messages": [/*somedata*/],
"users": [/*somedata*/],
"avatar": "/*somedata*/",
"_id": "/*somedata*/",
"type": "/*somedata*/",
"createdAt": "/*somedata*/",
"__v": 0
},
{
"messages": [/*somedata*/],
"users": [/*somedata*/],
"avatar": "/*somedata*/",
"_id": "/*somedata*/",
"type": "/*somedata*/",
"createdAt": "/*somedata*/",
"__v": 0
}
]
So in this reducer, i just want to replace or update the entire state array with my payload but without mutate my state. My payload also contains the same array of objects as above but with updated data.
const chatsReducer = (state = chats, {type, payload}) => {
switch (type) {
case '@updateChats':
return state = payload //i need something like this but without mutating
default:
return state
}
}
This should help you, it creates a new array and populates it with all the objects within your payload array.
const chatsReducer = (state=chats, {type, payload}) => {
switch (type) {
case '@updateChats':
return [ ...payload ];
default:
return [ ...state ];
}
}