0

I have an State varaible with array of objects like this.

type State = {
  Dp: ArrayDataProvider<string, Message>;
};

Inside Dp i will have data which will hold the data in the form of array like this.

 [{
    "id": 1,
    "name": "January",
    "abc": abc,
    "xyz": xyz
}, {
    "id": 2,
    "name": "February",
    "abc": abc,
    "xyz": xyz
}]

I want to replace the object which is having id 2 with the different object and i want to have my object like this .

 [{
    "id": 1,
    "name": "January",
    "abc": abc,
    "xyz": xyz
}, {
    "id": 2,
    "name": "New month",
    "abc": 1234abc,
    "xyz": someVlaue
}]

how to do it in efficient way with typescript in react. I have done something like this but not working

 const data = this.state.Dp?.data.slice();
  const index = data.findIndex(currentItem => {
    return currentItem.id === updateData[0].id;
  });
  data[index] = updateData;
  this.state.Dp.data = data;
  this.setState({ Dp: this.state.Dp });
Roster
  • 1,764
  • 6
  • 17
  • 36
  • 1
    `this.state.Dp.data = data;` mutates the current state, which is an anti-pattern in React. – Emile Bergeron Feb 18 '22 at 04:18
  • Does this answer your question? [How to update nested state properties in React](https://stackoverflow.com/questions/43040721/how-to-update-nested-state-properties-in-react) – Emile Bergeron Feb 18 '22 at 04:19

2 Answers2

1

I use map to do this:

const data = this.state.Dp?.data.map(currentItem => {
  return currentItem.id === updatedItem.id ? updatedItem : currentItem;
})

map creates a new array with the items from the previous array, but it gives you an opportunity to make adjustments to the items in the new array as it iterates through them. In my example, I'm checking the id of the item to see if it's the one you want to update, and swapping in your updatedItem if the ids match.

I'm not sure about the TypeScript part, to be honest. I haven't worked with it yet.

Note - I'm not sure what form your updateData is in, so you might have to adjust that. It seems like you want it to be an object, but in one of your lines you're treating it like an array.

Reed Dunkle
  • 3,408
  • 1
  • 18
  • 29
0

Use findIndex to find index of the object where id is equal 2, then replace new object to that place.

let tempArray = [...array];
const index = tempArray.findIndex((element) => element.id === 2);
tempArray[index] = {
  id: 2,
  name: "New month",
  abc: "1234abc",
  xyz: "someVlaue"
};
setArray(tempArray);
Rahul
  • 405
  • 1
  • 4
  • 15