Is It Possible to Use Async / Await in React Js?

I started programming in React Native, and I got used to use the syntax:

async myFunction(){
    ...
    return await otherFunction();
}

But I don't know how to make it compatible with React JS and React Native in a shared package. How can I accomplish this so that it works in both platforms?

Thanks!

2

3 Answers

If you building using create-react-app it's been available since v0.2.3

It can be used inside a Component like this

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { message: '' };
  }

  async componentDidMount() {
    this.setState({ message: 'loading...' });
    let d = await getData('/posts/1');
    this.setState({ message: d });
  }

  render() {
    let { message } = this.state;
    return (
      <div className="App">
        <p className="App-intro">
          { message }
        </p>
      </div>
    );
  }
}

See:

4

React Native ships with Babel and some Babel presets, whereas React on the web is just React related code.

If you want to use async/await on the web today you'll need Babel and the correct transforms:

or the stage-1 presets, which is fairly common in React apps today.

3

Alternatively you can use Typescript.

Since version 2.1 it is possible to use async/await and directly transpile to ES5 (in other words have it run on ~all browsers)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest