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

replace an array object in component state

My goal is to map over an array and replace objects that match a condition. Much like this working example:

const rows = [{
  "name": "Dad",
  "car": "Sedan"
}, {
  "name": "Mom",
  "car": "Sedan"
}]
const newCar = {
  "name": "Dad",
  "car": "Minivan"
}

const newArray = rows.map((r) => (r.name === newCar.name ? newCar : r))
console.log(newArray)

In my use case, component state contains the array, which is populated from an API.

  const [rows, setRows] = useState([])

Later, a change is required to one object in the array. The data variable contains the modified object to be merged into the array. I map over the array looking for matches on the _id field. When the _id matches, I return the object from data (the value to be merged into the array). When there is not a match, I return the object as it originally existed in state.

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

        setRows((rows) => [
          ...rows,
          rows.map((r) => (r._id === data._id ? data : r)),
        ])

The desired outcome is an array of the same size as the original. This new array should contain one modified object in addition to all original array values.

The actual results from the code above are that the modified data object is added rather than updated.

How can I change my code to replace the modified array element instead?

>Solution :

The useState() functional updates form calls a function and passes it the previous state. The Array.map() function returns a new arrays with the updated values. This means that you only need to map the previous state to get a new state:

setRows(rows => rows.map((r) => (r._id === data._id ? data : r)))
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