Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get spread operator updating state with React

I've defined my initial state in a Component as follows:

constructor(props) {
    super(props);
    //this.state = {count: props.initialCount};
    this.state = {
        timeArray: [],
        metawords: '',
        description: '',
        currentTime: '',
        inputFieldsDisabled: true
    }
}

I have an event that gets called and I want to just update the metawords property. I was thinking that the following code should work but it does not.

updateInputValue1(evt) {
    const newMetawords = "abcd";
    this.setState(
        [...this.state,{
            metawords: evt.target.value
        }]
    );

Thoughts?

like image 851
Peter Kellner Avatar asked Oct 15 '25 04:10

Peter Kellner


2 Answers

state is an object so updating it the way you are at the moment won't work.

You can simply update only the property you need as:

this.setState({
  metawords: evt.target.value,
})

Since you've mentioned spread operator, you can also (but not always necessary) update your state as:

this.setState({
  ...this.state,
  metawords: evt.target.value,
})

or

this.setState(prevState => ({
  ...prevState,
  metawords: evt.target.value,
}))

Should you need more info about it, I recommend you to have a look at ReactJS documentation.

like image 132
mersocarlin Avatar answered Oct 17 '25 17:10

mersocarlin


You can use spread operator like this to setState.

this.setState(
        {...this.state,
          metawords: evt.target.value
        })

However since you only want to change a single property, this will also work in your case:

this.setState({metawords: evt.target.value})
like image 30
Rohit Agrawal Avatar answered Oct 17 '25 17:10

Rohit Agrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!