Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this.setState return promise in react

I made my componentWillMount() async. Now I can using await with the setState.

Here is the sample code:

componentWillMount = async() => {
  const { fetchRooms } = this.props
  await this.setState({ })
  fetchRooms()
}

So question here is this.setState returns promise because I can use await with it?

Edit

When I put await then it runs in a sequence 1, 2, 3 And when I remove await then it runs 1, 3, 2??

  componentWillMount = async() => {
    const { fetchRooms } = this.props
    console.log(1)
    await this.setState({ } => {
      console.log(2)
    })
    console.log(3)
    fetchRooms()
  }
like image 884
Profer Avatar asked Nov 21 '18 09:11

Profer


People also ask

Does this setState return a promise?

setState uses callbacks and doesn't return a promise. Since this is rarely needed, creating a promise that is not used would result in overhead. In order to return a promise, setState can be promisified, as suggested in this answer.

How do you promise in setState React?

You can simple customize a Promise for setStatesetRooms = async () => { const { fetchRooms } = this. props; const { room } = await fetchRooms(); return new Promise(resolve => { this. setState({ roomId: room && room.

How do you get promise results in React?

To get promise value in React and JavaScript, we can use await . to create the getAnswer function that calls fetch with await to get the response data from the promise returned by fetch . Likewise, we do the same with the json method. And then we call setAns to set the value of ans .

What happens when setState is called React?

The state allows React components to change their output over time in response to user actions, network responses, etc, without violating their rules. It can be initialized in the constructor of a React component and afterward, can be accessed via the React component's class instance with the this object.


3 Answers

You can promisify this.setState so that you can use the React API as a promise. This is how I got it to work:

class LyricsGrid extends Component {    setAsyncState = (newState) =>     new Promise((resolve) => this.setState(newState, resolve)); 

Later, I call this.setAsyncState using the standard Promise API:

this.setAsyncState({ lyricsCorpus, matrix, count })   .then(foo1)   .then(foo2)   .catch(err => console.error(err)) 
like image 90
alki Avatar answered Sep 21 '22 01:09

alki


setState is usually not used with promises because there's rarely such need. If the method that is called after state update (fetchRooms) relies on updated state (roomId), it could access it in another way, e.g. as a parameter.

setState uses callbacks and doesn't return a promise. Since this is rarely needed, creating a promise that is not used would result in overhead.

In order to return a promise, setState can be promisified, as suggested in this answer.

Posted code works with await because it's a hack. await ... is syntactic sugar for Promise.resolve(...).then(...). await produces one-tick delay that allows to evaluate next line after state update was completed, this allows to evaluate the code in intended order. This is same as:

this.setState({ roomId: room && room.roomId ? room.roomId : 0 }, () => {   console.log(2) })  setTimeout(() => {   console.log(3) }); 

There's no guarantee that the order will stay same under different conditions. Also, first setState callback isn't a proper place to check whether a state was updated, this is what second callback is for.

like image 35
Estus Flask Avatar answered Sep 19 '22 01:09

Estus Flask


setState does not return a promise.

setState has a callback.

this.setState({
    ...this.state,
    key: value,
}, () => {
    //finished
});
like image 34
Tazo leladze Avatar answered Sep 20 '22 01:09

Tazo leladze