1

Feels like I'm frustratingly close to solving this, but not sure how to update all of the values in a given object array with useState. Here's an example:

    const [data, setData] = useState([
       {key: 1,
        value: 25},
       {key: 2,
        value: 30}
        ])

And then assume on a button click I want to add 10 to the value of every item in the array:

    const handleClick = () => {

    const newData = data.map(item => item.value + 10)

     setData ([
         ...data, ???

     ])

newData delivers an updated array, but I'm not sure how to use the Hook to update the state. Thanks!

2 Answers 2

2

You can make use of functional state updater and return the mapped result. Also note that since each value is an object you must clone and update just the value field

 const handleClick = () => {
     setData (prevData => data.map(item => ({...item, value: item.value+10})));
}

To put it in your way, it would be like

const handleClick = () => {

    const newData = data.map(item => { 
          return {...item, value: item.value + 10}
    });

     setData(newData);
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's exactly it. Thank you so much!
-1

You should setData to the result of your map iteration. It should be something like this:

const handleClick = () => {

   const newData = data.map(item => item.value + 10)

   setData(newData)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.