I have setup a useState hook as follows.
const [products, setProducts] = useState([
{
id: 1,
qty: 0,
},
{
id: 2,
qty: 0,
}
]);
I have a TouchOpacity component which fires the following function when pressed.
const _onPress = () => {
const productArr = products;
productArr[0].qty = value;
setProducts(productArr);
};
The expected outcome is that product with id 1 must increase the qty to 1, however this does not happen.
When i use the spread operator for the products from state as follows it works as expected.
const _onPress = () => {
const productArr = [...products];
productArr[0].qty = value;
setProducts(productArr);
};
What is the reason for this ?
productsconst productArr = products;not considered as copying an array ? I am creating a new variable right ?