I have a case like this
I have a current product
0: {id: "abc", name: "bigu", qty: 1, remarks: "nice"},
1: {id: "def", name: "moo", qty: 1, remarks: "handsome"}
When I add a new product
0: {id: "abc", name: "bigu", qty: 1, remarks: ""},
1: {id: "def", name: "moo", qty: 1, remarks: ""},
2: {id: "ghi", name: "ucing", qty: 1, remarks: ""},
3: {id: "jkl", name: "kepi", qty: 1, remarks: ""}
this is my first state and useEffect that change product list everytime I called addReq.product
const [productsLists, setProductsLists] = useState<Product[]>(addReq.product)
useEffect(() => {
setProductsLists(addReq.product)
}, [addReq.product])
I want the setProductsLists is not overwrite the current product that I already have and just adding a new product to the current array. The addReq is from my redux.
I already tried this methods but it causing infinite loops.
useEffect(() => {
setProductsLists(prevProducts => {
// Create a new array with the existing products and new products
const updatedProducts = [...prevProducts, ...addReq.product];
// Update the remarks of only the new products to an empty string
const updatedProductsLists = updatedProducts.map((product, index) => {
if (index >= prevProducts.length) {
return { ...product, remarks: "" };
}
return product;
});
return updatedProductsLists;
});
}, [addReq.product]);
2
Answers
you can use UseRef:
But, you should understand that changing productsList.ref does not re-render the component: no further changes occur(you cannot render newly modified "productsList").
you’d better consider using useSelector and useDispatch(with reducers).
calling setProducts will lead to a "modified" productList