Reputation: 103
I am trying to update a react state with these two objects where one is an array and another is object
DumpNames = [], {ActiveTab: '0'}
So if I put array object in setState as
this.setState({DumpNames})
Then it will create key-value
pair with DumpNames : []
.
How do I combine ActiveTab
object along with DumpNames
.
i.e. I want to do something like
this.setState({DumpNames,{ActiveTab}})
However If I try to put both these objects in an array and then destruct then it works fine.
let myObjects = [{DumpNames : DumpNames, ActiveTab : ActiveTab}]
this.setState(...myObjects)
Is there any other way I can accomplish this rather than destructing this way ?
Upvotes: 1
Views: 92
Reputation: 4734
With your last example
let myObjects = [{DumpNames : DumpNames, ActiveTab : ActiveTab}]
this.setState(...myObjects)
You're destructuring the array. So that's equal to:
this.setState({ DumpNames, ActiveTab });
This uses the object literal property value shorthand, so the above is equal to:
this.setState({
DumpNames: DumpNames,
ActiveTab: ActiveTab
});
So maybe you could define your component state like this:
class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
DumpNames: [],
ActiveTab: '0',
};
}
...
}
You can then modify the state with either key:
this.setState({ DumpNames: ['John', 'Doe'] })
or
this.setState({ ActiveTab: '1' })
or
this.setState({ DumpNames: ['Hello', 'Bye'], ActiveTab: '3' })
or
this.setState({ DumpNames, ActiveTab: '3' });
Upvotes: 1