'ReactJS: How to extend array with objects instead of replacing it in the redux state?
I'm trying to make an array of objects , but when I dispatch to the actions it replaces the exiting one. How do I fix that?
This is currently what I'm getting in the state:

shipmentGoods can have multiple goods having these properties like prodDescription etc.
When I add the next entry, it replaces the exiting one.
This is what I'm trying to do:
export const saveShipmentGoods = (data) => (dispatch) => {
dispatch({
type: GOODS_OR_PRODUCT_ADD,
payload: data
})
localStorage.setItem('shipmentGoods', JSON.stringify(data))
}
Reducer:
// Goods / Products portion
case GOODS_OR_PRODUCT_ADD:
const product = action.payload
const existProducts = state.shipmentGoods.find(
(x) => x.item === product.item
)
if (existProducts) {
return {
...state,
shipmentGoods: state.shipmentGoods.map((x) =>
x.item === existProducts.item ? product : x
)
}
} else {
return {
...state,
shipmentGoods: [...state.shipmentGoods, product]
}
}
I think there's a problem with my reducer. Please let me know how to fix that issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
