How to use await key word on react native?

React Native

React Native Problem Overview


I tried to use await/async on react native,but I got unexpected token error.

I added the code blow in my javascript source file:

var value = await AsyncStorage.getItem('STORAGE_KEY');

My react native version is 0.15.0.

Do I need to add some configuration to use async/await?

React Native Solutions


Solution 1 - React Native

I'm using async/await in my react native app and didn't have to do anything to configure or enable it in my project. My usage takes the form of...

async getCache(key){
    try{
        let value = await AsyncStorage.getItem(key);
        return value.json();
    }
    catch(e){
        console.log('caught error', e);
        // Handle exceptions
    }

}

Note: If you use an await inside a function that is not explicitly declared with async, you'll end up with an Unexpected token syntax error.

Solution 2 - React Native

> Do I need to add some configuration to use async/await?

Yes. async is still not a finalized part of the specification; they're currently considered "Stage 3" (Candidate).

You can enable all Stage 3 language proposals in your .babelrc by using the stage-3 preset. Alternatively, you can add just the async plugin.

Solution 3 - React Native

If you have a .babelrc file in the root of your project, you need to add the "react-native" preset:

npm i babel-preset-react-native --save-dev

Then in your .babelrc file add the following:

{
  "presets": ["react-native"]
}

More information here.

Solution 4 - React Native

After reading this comment on the react-native GitHub issues, the following worked for me:

Add the following npm module:

npm install babel-preset-react-native-stage-0 --save

Add the following configuration to your .babelrc file:

{ presets: ['react-native-stage-0'] }

Clear your cache:

$ watchman watch-del-all
$ ./node_modules/react-native/packager/packager.sh --reset-cache

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZackView Question on Stackoverflow
Solution 1 - React NativeChris GeirmanView Answer on Stackoverflow
Solution 2 - React NativeStephen ClearyView Answer on Stackoverflow
Solution 3 - React NativeAndrew TothView Answer on Stackoverflow
Solution 4 - React NativeJavid JamaeView Answer on Stackoverflow