So far as I've understood when I clone an array it gets immutable if I apply any action over its clone. Like here, for example:
const test = () => {
let array = [1,2,3,4]
let spreadArray = [...array]
spreadArray.forEach((item, i) => spreadArray[i] = 'changed')
console.log(array)
console.log(spreadArray)
}
<button>TEST</button>
As can be seen it works fine.
However I am trying to do that in ReactJs
with a props that I am receiving as an array from Redux
, I apply forEach over the clone array, but when I log the results I can see that both arrays have been changed.
My array is something like that:
const productsData = [
{
id: 1,
nome: 'Produto 1',
qtde: 10,
valor: 12.00
},
{
id: 2,
nome: 'Produto 2',
qtde: 100,
valor: 12.00
},
{
id: 3,
nome: 'Produto 3',
qtde: 90,
valor: 13.00
},
{
id: 4,
nome: 'Produto 4',
qtde: 100,
valor: 12.00
},
{
id: 5,
nome: 'Produto 5',
qtde: 80,
valor: 12.50
},
]
This what I am doing:
updateQtdeHandler = (arg, id) => {
let productsList = [...this.props.productsList]
productsList.forEach((product, i) => {
if (product.id === id) {
if (arg === 'up') {
productsList[i].qtde = product.qtde+1
productsList[i].valorTotal = product.qtde * product.valor
}
if (arg === 'down') {
productsList[i].qtde = product.qtde-1
productsList[i].valorTotal = product.qtde * product.valor
}
}
})
console.log(productsList) // CLONE
console.log(this.props.productsList) // ORIGINAL ARRAY
//BOTH ARRAYS ARE BEING CHANGED
}
I am receiving the array here:
const mapStateToProps = state => {
return {
productsList: state.productsDataState
}
}
Every place I looked support my understanding and I just don't get it.
What am I doing wrong here?
Or did I get something wrong and this actually should be the correct behavior when using redux?