Home > Enterprise >  Editing multiple object value in an object array with useState
Editing multiple object value in an object array with useState

Time:07-25

I have an object array similar to below

[array1, setArray1] = useState(
        [
        {
          name: "somename",
          count: 0,
          division: "somedivision",
          cost: 1000,
        },
        {
          name: "secondname",
          count: 0,
          division: "somedivision",
          cost: 2000,
        },
      ]
)

How can i individually update the cost value of each object in my list?

I was thinking of something like setArray1((previous) => ({...previous, cost: newcost}))

But how can i do this for multiple objects in an object array?

CodePudding user response:

const App = () =>{
  const [array, setArray] = React.useState([
        {
          name: "somename",
          count: 0,
          division: "somedivision",
          cost: 1000,
        },
        {
          name: "secondname",
          count: 0,
          division: "somedivision",
          cost: 2000,
        },
  ])
  const updateCosts = () => {
    let newCosts = [1002, 2006]
    setArray(previous => 
      previous.map((elem, index)=> {
        return({...elem, cost: newCosts[index]})
      })
     )
  }

  return(
    <div>
    <button onClick={()=>updateCosts()}>Update costs</button>
    { array.map(elem => <p key={elem.name}>{`Product ${elem.name} Cost ${elem.cost}`}</p>) }
    </div>
  )
}

ReactDOM.render(
    <App/>,
    document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

  • Related