Reputation: 1512
Here's the final data signature that I am saving in redux store.
const finalDataFormInReduxStore = {
"id": "123",
"id_details": [
{
"user_city": "SF",
},
{
"user_city": "SF",
}
}
Here's my simple action
export const updateUserCity = (index, city) => {
return {
type: UPDATE_USER,
payload: {
index,
city
}
};
};
The following reducer works where I am making the id_details property to be an object (but I wanted this prop to be an array as per my target data signature in redux store. )
case UPDATE_USER : {
return {
...state,
id_details: {
...state.id_details,
[actions.payload.index]: {
...state.id_details[actions.payload.index],
user_city: actions.payload.city
}
}
};
}
But, when I make id_details property to be an array the following reducer does NOT work . (which is what I wanted as per my target data signature in redux store. )
case UPDATE_USER : {
return {
...state,
id_details: [
...state.id_details,
[actions.payload.index]: {
...state.id_details[actions.payload.index],
user_city: actions.payload.city
}
]
};
}
I have looked at this github issue page for guidance, but did not help me . Probably I am missing something basic here.
Upvotes: 0
Views: 124
Reputation: 6052
From https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#updating-an-item-in-an-array the easiest way to do this is by mapping over the array:
case UPDATE_USER : {
return {
...state,
id_details: state.id_details.map((item, index) => {
if (index === actions.payload.index) {
return {...item, user_city: actions.payload.city};
}
return item;
}),
};
}
Upvotes: 2