1

I am trying to set multiple state properties at same time, but since setState() is asynchronous I've to use callback, but as more properties I have to edit at one time this code becomes more & more ugly!

Is there any other good way to achieve this?

this.setState(
  {
    item_1: true
  },
  (e => {
    this.setState(
      {
        item_2: false
      },
      (e => {
        this.setState(
          {
            item_3: 'Hello World'
          }
        )
      })
    )
  })
)
1
  • 1
    Why did you think you could only update one value at a time? Commented Jun 15, 2017 at 6:44

2 Answers 2

6

It's quite possible to set them all in one go, like this:

this.setState({
    item_1: true,
    item_2: false,
    item_3: 'Foo'
});

If you still want to make certain change after state change, you can still use callback with this. like setState({obj},callback);

Sign up to request clarification or add additional context in comments.

Comments

2

@HoriaComan answer is correct but to provide more info.

Yes, setState is asynchronous but asynchronous behaviour comes into play when your other input depends on the previous output,

In your case all the state values are independent. So you can directly set the state like

this.setState({
    item_1: true,
    item_2: false,
    item_3: 'Foo'
});

You will want to use a callback in case when you want to use the updated state just after setting it for instance

this.setState({
    item_1: true,
    item_2: false,
    item_3: 'Foo'
}, ()=> {
     console.log(this.state.item_1, this.state.item_2, this.state.item_3);
});

Comments

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.