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?
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?
Share Improve this question asked Dec 5, 2017 at 6:21 Peter KellnerPeter Kellner 15.5k28 gold badges112 silver badges201 bronze badges 1 |3 Answers
Reset to default 11state
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.
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})
Why not simply:
this.setState({ metawords: evt.target.value })
You don't need to pass all other state values, just pass the property and the new value, that you want to update. You don't need to bother about the other state values during setState, React will do the merging (merging of all other state values and the state that you wants to update).
For more details check DOC.
this.setState([...this.state,{metawords: evt.target.value}])
. – Madhavan.V Commented Dec 5, 2017 at 6:27