update State react hook JSON data

I’m trying to update the State(JSON data). The initial state is an empty object because will be populated with “tree”(json data) on first render( the tree data is coming from a promise, so i tried to simulate that with a useEffect). The problem is that i don’t know how to update the “val” property from “tree” with the value from each slider(target.value).

import React, {useEffect, useState} from 'react'
import ReactDOM from 'react-dom'
import Slider from './slider'


let data = [
  {id: 'Item 1', index: 0, name: 'Item 1'},
  {id: 'Item 2', index: 1, name: 'Item 2'},
  {id: 'Item 3', index: 2, name: 'Item 3'},
  {id: 'Item 4', index: 3, name: 'Item 4'},
  {id: 'Item 5', index: 5, name: 'Item 5'},
  {id: 'Item 6', index: 6, name: 'Item 6'},
  {id: 'Item 7', index: 7, name: 'Item 7'},
  {id: 'Item 8', index: 9, name: 'Item 8'},
  {id: 'Item 9', index: 12, name: 'Item 9'},
]
let data2 = [
  {id: 1, val: 0.5088961783678},
  {id: 2, val: 0.074147856793482},
  {id: 3, val: 0.074147856793482},
  {id: 5, val: 0.074147856793482},
  {id: 6, val: 0.074147856793482},
  {id: 7, val: 0.074147856793482},
  {id: 0, val: 0.097068824077823},
  {id: 9, val: 0.074147856793482},
  {id: 12, val: 0.074147856793482},
]

function App() {
  const [values, setValues] = useState({})


  function handleChange(index, value) {
    setValues() 
  }

  
  let tree = {}
    data2.forEach((v) => {
      tree[v.id] = (v.val * 100).toFixed()
    })
    

  
  React.useEffect(() =>{
    setValues(tree)
  },[])

    
  return (
    <>
      {data.map((item, index) => (
        <Slider
          key={item.id}
          value={values[item.index]}
          title={item.name}
          onChange={(e) => handleChange(index, e.target.value)}
        />
      ))}
    </>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

Answer

You can update the state like this:

function handleChange(index, value) {
  setValues((prevState) => {
     return { ...prevState, ...{[index]: value}};
  });
}

Sandbox: https://codesandbox.io/s/frosty-davinci-p5d7k?file=/src/App.js:992-1125