Jack
Jack

Reputation: 21

The best way to modify react state property with React Hooks

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

Upvotes: 1

Views: 47

Answers (1)

Stuck
Stuck

Reputation: 12292

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

Upvotes: 3

Related Questions