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

Updating a value in a React state array

I’m trying to update a very simple state array.

Here’s how I am initializing the array.

const [total, setTotal] = useState([0,0,0]);

I also have an index to keep track of called, option

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

To make it simple, I just need a function that takes in ‘price’ as an argument and adds it to the state array named ‘total’

const addToTotal = (price) => {setTotal(total[option] += price)}

I know I have to use the spread operator to update and that this is incorrect, but I hope this gives an idea of what I’m trying to do.

Edit: Sorry that there is a little confusion. When I said ‘add’, I want to increment the number in that specific array.

If
option = 1 then I ‘add’ 1 it, the result should be [1, 0, 0]

>Solution :

One way of doing it is by using map to update the state

const addToTotal = (price) => {
    const newState = total.map((t, i) => i === option ? t + price : t)
    setTotal(newState)
)}
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