I'm confused by the behavior of a copied/cloned array of objects and their values inside a setInterval() function call.
Say I have a »state« which is an array of objects, each object has a key holding a numeric value…
const state = [
{
id: 'a',
valueToIncrement: 0
},
...
]
When I copy the original state array inside the handler function of a setInterval()
call (using the spread operator) and then increment the value of any of the objects inside this new state array…
const interval = setInterval(() => {
///////////////////
// Copy state... //
///////////////////
const newState = [...state];
////////////////////////
// ...increment value //
////////////////////////
newState[0].valueToIncrement = newState[0].valueToIncrement + 1;
console.log(newState)
}, 1000);
…I'm expecting the new value of this object to always be the original value + 1, since at the start of the handler function the original state is copied.
However, that is not what happens. It seems the incremented value is being preserved across calls of the handler function. When logging the copied state at the end of each handler call, I can see the value of the modified object increasing. Why is that? Shouldn't the value be reset since it is always copied from the original?
(Snippet to demonstrate)
const state = [{
id: 'a',
valueToIncrement: 0
}]
const interval = setInterval(() => {
///////////////////
// Copy state... //
///////////////////
const newState = [...state];
////////////////////////
// ...increment value //
////////////////////////
newState[0].valueToIncrement = newState[0].valueToIncrement + 1;
console.log(newState)
}, 1000);