Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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!

Did you look at AsyncStorage in react native official documents? (edit: just noticed this is asked months ago) – eden Mar 1, 2017 at 12:41 @EnieJakiro I don't know how AsyncStorage is related to the question. I do use AsyncStorage but only for React Native. – Santiago Bendavid Mar 2, 2017 at 14:50

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

https://github.com/facebookincubator/create-react-app/releases/tag/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 }

https://github.com/facebookincubator/create-react-app/issues/1024

thanks, but it's not working with arrow functions. I use arrow function to avoid extra line of code for binding this in constructor. Any tip on how to make it compatible with arrow functions. I am using CRA – Vaibhav Vishal Jan 17, 2019 at 12:10

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: https://babeljs.io/docs/plugins/transform-async-to-generator/

or the stage-1 presets, which is fairly common in React apps today. http://babeljs.io/docs/plugins/preset-stage-1/

Thanks for your answer @azium. I installed both and after running "npm run dev" I get the error "Unexpected token" for the async function – Santiago Bendavid Jul 13, 2016 at 16:53 You're going to have to show more about your project to diagnose.. can you post your package.json and webpack.config.js files? – azium Jul 13, 2016 at 17:53

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.