Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for AsyncStorage.getItem()

I am using AsyncStorage in my React Native application to store information about the user. The getItem() function is asynchronous and requires me to implement a callback when I want to load data from the storage system.

AsyncStorage.getItem("phoneNumber").then((value) => {     this.setState({"phoneNumber": value}); }).done(); 

Because retrieving a value from the storage does not take long, I would like to wait until the operation is complete before continuing execution.

Is it possible to load data in a way that is not Asynchronous? If not, is there an easy way for me to wait until the getItem() call is complete to continue executing?

like image 963
Adam Jakiela Avatar asked May 09 '16 15:05

Adam Jakiela


People also ask

What does AsyncStorage getItem return?

getItem() returns a single value AND a promise.

Is AsyncStorage deprecated?

Deprecated. Use one of the community packages instead. AsyncStorage is an unencrypted, asynchronous, persistent, key-value storage system that is global to the app. It should be used instead of LocalStorage.


2 Answers

You can try either add a then after your getItem.

AsyncStorage.getItem("phoneNumber").then((value) => {     this.setState({"phoneNumber": value}); }) .then(res => {     //do something else }); 

Or use await to wait the async operation to finish

var value = await AsyncStorage.getItem(STORAGE_KEY); //use value to do something else. 
like image 148
Fan Jin Avatar answered Oct 11 '22 14:10

Fan Jin


try this option and you will not get the

Syntax Error: Await is a reserved word

async getData() {     return await AsyncStorage.getItem("@App:KEY"); } 
like image 40
Gal Zalait Avatar answered Oct 11 '22 14:10

Gal Zalait