1

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 ?

1 Answer 1

1

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' }); 
Sign up to request clarification or add additional context in comments.

4 Comments

There isn't anything to imply that the OP would have put the setState function inside the render function
@BlakeSteel The subject of matter is setting the state. The question implies that the OP is relatively new to this subject, so it could be worth mentioning to help.
@Alserda, You see this.setState({DumpNames}) this is how I am putting it in the state. My question was how to put ActiveState along side this object. I am totally aware of re-rendering. None of your statements I found worthy. Since I am looking out something like DumpNames without key-value pair and ActiveState with key-value pair in one setState method
@user10005648 this.setState({ DumpNames, ActiveTab: 3 });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.