0

In React js component I have this code

this.state.author[field] = value;

In the console I got a warning: Do not mutate state directly. Use setState()

How could I put author with [] in setState?

amorenew
  • 10,760
  • 10
  • 47
  • 69

2 Answers2

2

If field is a variable that holds the key, you can do this:

this.setState({author: {...this.state.author, [field]: value}})
Psidom
  • 209,562
  • 33
  • 339
  • 356
1
**

React uses setState function to update the state of component, you can do somethings like below

**

let newAuthor = [...this.state.author];
newAuthor[field] = value;
this.setState({author:newAuthor});
mindaJalaj
  • 448
  • 3
  • 11