I try to increment a quantity property in an array of objects with React. But I can't figure out how I can reach the item to update.
What I tried:
const initialState = {
items: [{
id: 254,
quantity: 1
},
{
id: 493,
quantity: 1
}
],
};
const payload = {
id: 254
};
function updateProduct(state, action) {
return state.items.map((item, i) => {
if (item.id === action.id) {
return {
...state,
items: [
...state.items,
{
[i]: {
quantity: state.items[i].quantity + 1
}
}
]
};
}
});
}
The returned object should be:
{
items: [{
id: 254,
quantity: 2
},
{
id: 493,
quantity: 1
}
],
}
Thanks for your help !