Dale Jefferson

Dale Jefferson

Father, Husband, Classical Liberal, Software Developer

ES7 Async/Await with React Native

By Dale Jefferson. Published
JavaScript, Async Await, React Native

Async/Await is a new syntax for writing asynchronous code in JavaScript. Support was added in React Native 0.10 and it’s now reached TC39 stage 3 (candidate).

Example

In this example using the promise returning fetch polyfill. We will display the React Native GitHub star count.

const URL = "https://api.github.com/repos/facebook/react-native";

class StarCount extends Component {
  constructor() {
    super();

    this.state = {stars: "?"};
  }

  componentDidMount() {
    this.fetchData().done();
  }

  async fetchData() {
    const response = await fetch(URL);
    const json = await response.json();
    const stars = json.stargazers_count;

    this.setState({stars});
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.text}>
          React Native has {this.state.stars} stars
        </Text>
      </View>
    );
  }
}

Async / await works with any Promise based API or one of your creation.

const getStars = () =>
  new Promise(resolve => {
    const FIVE_SECONDS = 5000;
    // Simulate async operation
    setTimeout(() => resolve(1234), FIVE_SECONDS);
  });
const fetchData = async () => {
  const stars = await getStars();
  // Do something with stars
};