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
CodePudding user response:
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.
CodePudding user response:
The objects are the same in memory even though I changed the reference.
"A variable assigned to an object stores not the object itself, but its “address in memory” – in other words “a reference” to it."
I used _.cloneDeep from https://lodash.com/docs/4.17.15#cloneDeep
So I changed my code to:
const prevProducts = _.cloneDeep(allProducts);
setProducts(prevProducts);
Another solution: In case you do not want to use lodash.clonedeep package, you can do the same using below:
const array = [{a: 1}]//initial array
const copy = array.map(item => ({...item}))