Home > front end >  Updating a value in a React state array
Updating a value in a React state array

Time:12-10

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

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]

CodePudding user response:

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)
)}

CodePudding user response:

Use the callback in usestate set method

  const addToTotal = (price) => {
    setTotal(prev => {
     prev[option]  = price
     return prev
    }
  )}
  • Related