Here I am trying to update my state data with a reducer. I am sending an object through dispatch which is consisted of id, and some data. By this id, I am trying to update a specific object of my state. My state reducer is,
case "UPDATE_USER_SUCCESS":
return {
...state,
users: state.users.map((user) => {
if (user.id !== action.payload.id) {
return user;
} else {
return {
...user,
...action.payload,
};
}
}),
};
Here is the action,
export const updateUser = (updatedUser) => (dispatch, getState) => {
dispatch({
type: "UPDATE_USER_SUCCESS",
payload: updatedUser,
});
console.log(updateUser);
localStorage.setItem(
"Users",
JSON.stringify(getState().addUserReducer.users)
);
};
ANd my dispatching is from here,
const formHandler = (e) => {
e.preventDefault();
dispatch(updateUser(updatedUser));
console.log(name + email + phone + roles);
};
return {
...user,
...action.payload,
};
what is your goal here? If user was an array, by utilizing this code , you would add action.payload to your array. But user is an object. If you want to pass another object to it, you have to give it a key:
return {
...user,
whateverkey:action.payload,
};
and your user objcect has a new key-value pair. furthermore: if you want easier access further on you can use this as well:
return {
...user,
id:action.payload.id,
name:action.payload.name,
address:action.payload.address
};