demonofthemist
demonofthemist

Reputation: 4199

Avoid React setState() callback loop

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'
          }
        )
      })
    )
  })
)

Upvotes: 1

Views: 462

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281626

@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);
});

Upvotes: 2

Horia Coman
Horia Coman

Reputation: 8781

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);

Upvotes: 6

Related Questions