push function changes props in react

1.7k Views Asked by At

this is my problem.

when I use the push() function it changes my props in react.

const prioship = (this.props.orders.prioshipping === false ? {'name':`Regular Shipping`,'price':'0','currency':'EUR','quantity':1, 'description': ''} : {'name':`Priority Shipping`,'price': this.props.prices.shipping['A'].toString() ,'currency':'EUR','quantity':1, 'description': ''})
console.log('#### TOKEN ORDER #####1', this.props.orders.warenkorb)
const orders = this.props.orders.warenkorb
const order2 = this.props.orders.warenkorb

orders.push(prioship)
console.log('#### TOKEN ORDER #####2',order2, this.props.orders.warenkorb)

So even at the level of the console log 'TOKEN ORDER 1' this props have the "prioship" in it even though it happens later in the code. I don't understand how to make it stop this. I just want a variable 'orders' where the prioship is in it, i dont want my props to change.

Please help

3

There are 3 best solutions below

0
On

Never mutate props, which you're doing here.

Make a new array instead, and don't modify the original array.

const orders = this.props.orders.warenkorb.concat( prioship );

Array.push() "mutates" (changes/modifies) the original array. Array.concat() returns a new array, and does not modify the original.

0
On

As Andy Ray mentioned, don't change the props directly.

The right way is to use const orders = this.props.orders.warenkorb.slice(), which will give you a copy of the array in the props and allow you to use this array later without changing the original props.

Lastly, the reason your 1st console.log('#### TOKEN ORDER #####1', this.props.orders.warenkorb) is showing you the later value is because the console will show the values by reference. If you want the exact value at where you're printing you can use: console.log('#### TOKEN ORDER #####1', JSON.stringify(this.props.orders.warenkorb));

0
On

Two things are happening here.

First of all you are modifying a prop in an object. even if you save the property in another variable all you are doing is saving a reference to that property. If you want to avoid that you can use concat as Andy Ray pointed out.

Second thing. You see the change even at TOKEN ORDER 1 because console.log can be a bit tricky. Since objects store references to their properties, if you change the object later it will show you the latest update. More on this here.