await setState in react-native

Alexander Kuttig
Horizon Alpha
Published in
2 min readJan 30, 2018

Since I am a big fan of ES7 async/await syntax for developing react-native apps, there are plenty of situations where I am annoyed that I can only use a callback but no promise on setState. That makes it impossible to use async/await on setState.

Hintergrundbild: Master1305/Shutterstock.com

Look at the following example I borrowed from https://medium.com/front-end-hacking/es7-async-await-with-react-native-35ca167cc326 (only changed it a bit)

Here we have three problems.

  1. The syntax looks very ugly, especially when we are setting states multiple times in a row.
  2. We are not able to return anything from the fetchData function, after setting the state.
  3. We have no guarantee, that our setState is completed, when going on in our componentDidMount

So, there is a simple solution for making setState “awaitable”. You can wrap it in a Promise as you can see in the following example.

We use a Promise which gets resolved inside the callback of the setState. That makes it “awaitable” and solves our three problems.

  1. We can now use it multiple times without going to callback hell.
  2. We would be able to return something from our fetchData function, after setting the state
  3. Awaiting the fetchData function now means also to await the setState, which means that we can rely on the state to be set now.

Because of this points, we are using this code in all our projects. We build our own PromiseComponent, which makes our promiseSetState available without redefining it in all our Components.

If you are interested, you can find it on npm here: https://www.npmjs.com/package/react-native-promise-component (install with npm i react-native-promise-component

I appreciate your feedback. If you have any comments, please drop me a line.

--

--