1

Lets assume I have defined my React state using hooks like that

const items = [{name: 'Jack', age: 1},{name: 'Bill', age: 2},{name: 'Jason', age: 4}];

const [content, setContent] = useState<{name: string, age: number}[]>(items);

What is the best way to modify second element of the array?

This is the way how I am doing it at the moment

const newContent = content.map((item,i) => {
if(i == 1){
   return(...item, age: 5)
}
else{
    return item;
}
})
setContent(newContent)

Thanks

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Jack
  • 21
  • 3
  • 1
    `{ ...item, age: 5 }` with curly braces for objects, not parentheses. – Emile Bergeron Apr 22 '20 at 17:02
  • 1
    Does this answer your question? [Whats the best way to update an object in an array in ReactJS?](https://stackoverflow.com/questions/28121272/whats-the-best-way-to-update-an-object-in-an-array-in-reactjs) – Emile Bergeron Apr 22 '20 at 17:02

1 Answers1

3

You can use the previous state by giving the setter a function and need to use the correct curly brackets.

const index = 1; // the index you want to update
const newAge = 5; // the value you want to set

setContent(prev => prev.map((item, i) => {
    if (i === index) {
      return { ...item, age: newAge };
    }
    return item;
  }
);
Stuck
  • 11,225
  • 11
  • 59
  • 104