Update A Property In An Array Of Objects
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:
Solution 1:
I will suggest a few changes:
- Use the convention of action with {type, payload}
- Perform the action in a reducer.
so this yields:
const reducer = (state, action) => {
const {type, payload} = action;
switch(type) {
case 'update_quantity':
const {id: itemId, quantity} = payload
return ({
...state,
items: state.items.map(item => (item.id === itemId ? {...item, quantity} : item)
default:
return state;
}
}
and then, to update:
dispatch({type: 'update_quantity', payload: {id: 'xxx', quantity: 3}});
Solution 2:
Seems like you digged a little deep there. Based on the data you provided, isnt this as simple as:
function updateProduct(state, action) {
return state.items.map((item, i) => {
if (item.id === action.id) {
return {
...item,
quantity: item + 1
}
} else {
return item
}
});
}
Solution 3:
first of all you have to clone/store your arr state/values in new variable
let state = [...initialState.items] // now you have all the values in state var
// and then mutate the state
let mutatedState = state.map(el => {
//modify data how you need
});
// Then assign mutatedState to initialState.items
initialState.items = mutatedState
};
Solution 4:
Assuming you want
{
items: [{
id: 254,
quantity: 2
},
{
id: 493,
quantity: 2 // <<<<<<<<<<<< 2 here as well
}
],
}
and also assuming you can use the latest and greatest of ECMA Script:
const initialState = {
items: [{
id: 254,
quantity: 1
},
{
id: 493,
quantity: 1
}
],
};
const reduceIncrementQuantity = (item) => ({...item, quantity: item.quantity + 1});
const reduceIncrementQuantities = (state) => ({items: state.items.map(reduceIncrementQuantity)});
console.log(reduceIncrementQuantities(initialState));
Solution 5:
You can write this as,
function updateProduct(state, action) {
return { ...state,
items: state.items.map(item => ({
...item,
quantity: action.id === item.id ? item.quantity + 1 : item.quantity
}))
}
}
Post a Comment for "Update A Property In An Array Of Objects"