DEV Community

Cover image for Async/Await with React Lifecycle methods
Dale L. Jefferson
Dale L. Jefferson

Posted on • Edited on • Originally published at dalejefferson.com

Async/Await with React Lifecycle methods

If you are like me you will also end up doing a lot of asynchronous work in componentWillMount/componentDidMount. This article will show you how to use Async/Await with React's Lifecycle events. React’s lifecycle methods can return any value, including a promise.

Promise Version

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

Async/Await Version

async componentDidMount() {
  const res = await fetch('https://example.com')
  const something = await res.json()

  this.setState({something})
}

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

I personally find the Async/Await version much easier to read.

Full example (React Native)

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

Top comments (0)