Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use await key word on react native?

Tags:

react-native

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?

like image 867
Zack Avatar asked Dec 01 '15 09:12

Zack


People also ask

What is async () in React Native?

By Aman Mittal | 6 min read. AsyncStorage is a simple, asynchronous, unencrypted by default module that allows you to persist data offline in React Native apps. The persistence of data is done in a key-value storage system. There are numerous scenarios where this module can be beneficial.

How do you use await?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

What is await keyword React?

The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.

Can I use await inside useEffect?

React can run this async function but can not run the cleanup function. Don't use raw async function directly in the useEffect.


1 Answers

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.

like image 95
Chris Geirman Avatar answered Sep 21 '22 07:09

Chris Geirman