Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React JS – How to update State Array in real time?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

useEffect(() => {console.log(quantities)}, [quantities])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading