Reputation: 353
const initialState = []
case UPDATE_USER: {
console.log(action, "this is action");
return [
...state,
state.map(
user =>
user.name === action.oldName
? {
...user,
name: action.newName
}
: user
)
];
}
so I have this initial state. and then this is one of my case statements for the reducer
Im trying to replace an object (a user) with a new user object. so im trying to map over the array and then replace it with the old and new name. the old and new names are coming through correctly. however this currently is changing an array of 10 objects to an array of 10 objects plus the last item of the array being an array of 10 objects. very confusing but essentially
the array is growing from length 10 to length 11
even though it should stay the same
and the last item of the array (which is an array itself) is the array I want in the new state
if that makes sense?
basically it's close but not quite there
Upvotes: 0
Views: 1383
Reputation: 281656
Instead of using the spread syntax
, all you need to do is to return the mapped value
, since you are iterating through your reducer state and individually cloning the inner objects in the map.
case UPDATE_USER: {
console.log(action, "this is action");
return state.map(
user =>
user.name === action.oldName
? {
...user,
name: action.newName
}
: user
)
}
Upvotes: 2