Reputation: 79
I have this code which every time, when button is clicked should filter product by entered value by user. This part works fine, but every time I try to add another product, it overwrites already mapped value. But I need to keep all entered products in the setLoadedProducts state.
const [loadedProducts, setLoadedProducts] = useState([]);
const [expeditionProducts, setExpeditionProducts] = useState([]);
const addProduct = () => {
const enteredProductEan = enteredEanRef.current.value;
const filteredExpeditionProducts = expeditionProducts.filter(
(order_item) => {
return order_item.ean.toString() === enteredProductEan;
}
);
const loadedExpeditionProducts = filteredExpeditionProducts.map(
(invoiceData) => {
return invoiceData;
}
);
setLoadedProducts(loadedExpeditionProducts);
setExpeditionProducts(
expeditionProducts.filter(function (item) {
return !filteredExpeditionProducts.includes(item);
})
);
Upvotes: 1
Views: 334
Reputation: 166
If you want to keep adding more products to loadedProducts
without losing what you've already saved, you can include the value of your existing loadedProducts
when you update state:
const newLoadedExpeditionProducts = filteredExpeditionProducts.map(
(invoiceData) => {
return invoiceData;
}
);
setLoadedProducts(loadedProducts => [...loadedProducts, ...newLoadedExpeditionProducts]);
Upvotes: 2