I made my componentWillMount()
async. Now I can using await
with the setState
.
Here is the sample code:
compon
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.