Reputation: 1113
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?
Upvotes: 55
Views: 53273
Reputation: 9009
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
Upvotes: 1
Reputation: 9684
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.
Upvotes: 62
Reputation: 419
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.
Upvotes: 5
Reputation: 456687
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.
Upvotes: 7