Search code examples
reactjsredux

How do i stop redux state from mutating


This is mutating my redux state somehow. I don't know why: allProducts is a state in my store with initial_state of [] and gets values from api call.

const [products, setProducts] = useState([])

const prevProducts = [...allProducts];
setProducts(prevProducts);

const updateProductPrice = (newPrice, index) => {
 const newProducts = [...products];
 newProducts[index].price = newPrice;
 setProducts(newProducts);
 console.log(allProducts);
}

When I console.log(allProducts), it's showing me an updated array that has the values of newProducts


Solution

  • I think what you are seeing has to do specifically with how JavaScript is storing object references inside your arrays. When you copy an array, you do not do a full re-creation of all the objects in it, even when using the spread operator, you are only copying the references to the objects at each index.

    In other words, assuming they share matching indexes, each item at newProducts[i] === allProducts[i] - i.e. is the exact same object instance.

    See, for example, https://javascript.info/object-copy and as well there are many references for "shallow" and "deep" copying for objects.