DEV Community

Cover image for ES7 Async/Await with React Native
Dale L. Jefferson
Dale L. Jefferson

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

1 1

ES7 Async/Await with 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
};

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →