ES7 Async/Await with React Native
Dale L. Jefferson
Posted on May 30, 2019
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
};
💖 💪 🙅 🚩
Dale L. Jefferson
Posted on May 30, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
react How to build type-enforced UI components in React Native using @shopify/restyle
November 28, 2024
beginners Are You Team Apple or Android? An Intro to React Native for Mobile App Development So You Don’t Have to Choose
November 18, 2024