amorenew
amorenew

Reputation: 10896

Reactjs setstate by field

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?

Upvotes: 0

Views: 616

Answers (2)

mindaJalaj
mindaJalaj

Reputation: 448

**

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

Upvotes: 1

akuiper
akuiper

Reputation: 214957

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

this.setState({author: {...this.state.author, [field]: value}})

Upvotes: 2

Related Questions