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

Editing multiple object value in an object array with useState

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

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

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

>Solution :

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