Home > Net >  React JS - How to update State Array in real time?
React JS - How to update State Array in real time?

Time:11-28

I have a simple UseState quantity array that is updated onClick of a button. In the onClick event a new array is created updating a specific objects quantity value. Then that new array is set to be the quantity array. But for some reason the array does not update in real time. For example if the second item's quantity gets updated the new array gets created with the new values. but the original array remains the same. However if we click the button again, this time the original array will get updated but to the previous value of the new array.

I will provide the codes and console logs of the two arrays.

/*state array for quantity*/
    const [quantities, setQuantities] = useState([
        {id: 1, quantity:0},
        {id: 2, quantity:0},
        {id: 3, quantity:0},
        {id: 4, quantity:0},
        {id: 5, quantity:0},
        {id: 6, quantity:0},
        {id: 7, quantity:0},
        {id: 8, quantity:0},
        {id: 9, quantity:0},
        {id: 10, quantity:0}]);
/*Incrementing Quantity*/
            const increment = () =>{
                const newQuantity = quantities.map(obj => {
                    if (obj.id === info.id) {
                      return {...obj, quantity: obj.quantity 1};
                    }
                    return obj;
                  });
                  console.log(newQuantity)
                setQuantities(newQuantity);
                console.log(quantities)
            }

The console logs

CodePudding user response:

setState is asynchronous in react. It wil not update the state immetidaly. Can use useEffect to check once updated

useEffect(() => {console.log(quantities)}, [quantities])
  • Related