Reputation: 1735
The below Reducer supposed to update quantity of particular object in state when I dispatch {"id": 14, 'quantity':3}
or {"id": 14, 'quantity':2}
.
const initialState={ items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}] }
const cart =(state=initialState,action)=>{
switch(action.type){
case 'UPDATECART':{
//need updating code here
}
default: return state
}
}
export default cart
How can I update particular object in state's array, keeping other values unaltered ?
The updation function increment quantity
of existing object by 1
and id
will be permanent.
Proposed work flow
CURRENT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':1},{"id": 25,'quantity':1}]
INCOMING OBJECT : {"id": 15,'quantity':2}
EXPECTED RESULTANT STATE : items = [ {"id": 14, 'quantity':1},{"id": 15,'quantity':3},{"id": 25,'quantity':1}]
Upvotes: 0
Views: 69
Reputation: 348
Try this:
case 'UPDATECART':{
//need updating code here
return state.map( cart => cart.id === INCOMING_OBJECT.id ? {...cart, quantity:
cart.quantity + INCOMING_OBJECT.quantity}: cart )
}
Upvotes: 1
Reputation: 619
You should replace the item in the array and return new state reference, try the following code
const initialState = {
items: [
{ id: 14, quantity: 1 },
{ id: 15, quantity: 1 },
{ id: 25, quantity: 1 }
]
};
const cart = (state = initialState, action) => {
switch (action.type) {
case "UPDATECART": {
const index = state.items.findIndex(
item => item.id === action.payload.id
);
if (index >= 0) {
state.items[index] = {
id: action.payload.id,
quantity: action.payload.quantity
};
} else {
// add to array if not exist
state.items.push({
id: action.payload.id,
quantity: action.payload.quantity
});
}
return {
items: [...state.items] // creating new array
};
}
default:
return state;
}
};
export default cart;
Upvotes: 1
Reputation: 187
Try:
case UPDATE CART:
const items = state.items;
const {id, quantity} = INCOMINGOBJECTORPAYLOAD; // destructure new object in 1 line
const oldQuantity = items.filter(item => item.id === id)[0].quantity
return {
[...items, {"id": 15,'quantity':oldQuantity+quantity}]
};
Please note that ...items
is the 'spread' operator used to populate the array with old items (which don't need any change)
Upvotes: 1