Home > Software engineering >  replace an array object in component state
replace an array object in component state

Time:12-19

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.

        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?

CodePudding user response:

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)))
  • Related