Async Await with React Lifecycle methods

Dale L. Jefferson
Frontend Weekly
1 min readDec 29, 2016

--

React’s lifecycle methods can return any value, this is useful when combined with async await. If you compare that with the promise version, I personally think it’s much easier to read.

async componentDidMount() {
const res = await fetch('https://example.com')
const something = await res.json()
this.setState({something})
}
componentDidMount() {
fetch('https://example.com')
.then((res) => res.json())
.then((something) => this.setState({something}))
}

Note if you do return a promise from the lifecycle methods it will be not be awaited.

Full example

class AwesomeProject extends Component {
state = {}
setStateAsync(state) {
return new Promise((resolve) => {
this.setState(state, resolve)
});
}
async componentDidMount() {
StatusBar.setNetworkActivityIndicatorVisible(true)
const res = await fetch('https://api.ipify.org?format=json')
const {ip} = await res.json()
await this.setStateAsync({ipAddress: ip}) StatusBar.setNetworkActivityIndicatorVisible(false)
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
My IP is {this.state.ipAddress || 'Unknown'}
</Text>
</View>
);
}
}

--

--