Home > Software engineering >  React JS - Why array objects reset after updating?
React JS - Why array objects reset after updating?

Time:11-28

I have an array of objects which has an id and price. When the onClick event happens it updates the price of a specific object. However when the onClick event happens again, it is shown that the relevant item's price is updated. However, the previous item's price which was updated is now resetted back to the default value. Anyone knows why this happens? The array is mapped from another array and initialized when the page loads and the updating happens inside a function which gets called upon a button click.

/*array for prices*/
    const prices = [];
    props.cartItems.slice(1).map(
        (data) => {
            prices.push({id: data.id, price: parseInt(data.price)});
        }
    )
/*Function to update price*/
            const calculateTotalPrice =()=>{

                let objIndex = prices.findIndex((obj => obj.id == info.id));
                prices[objIndex].price = info.price*found.quantity;
            }

CodePudding user response:

You need to store your information inside of state, or on a backend side or in some other storage, otherwise it will be lost after re-render.

So for better understanding, imagine that re-render works like page reload, and all stuff that is not in state or something just re-initialized.

So when you have your prices array and update one thing there you see the results, but when you try to modify something else, all processes starts from scratch, so your prices array will get fresh data from car items (that doesn't actually have a updated price that was previously updated) and will set new price.

So to solve this, you need to store in state car items and update prices there through manipulating state.

  • Related