32

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?

David Schumann
  • 13,380
  • 9
  • 75
  • 96
Adam Jakiela
  • 2,188
  • 7
  • 30
  • 48

3 Answers3

38

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.
David Schumann
  • 13,380
  • 9
  • 75
  • 96
Fan Jin
  • 2,412
  • 17
  • 25
  • 4
    Syntax Error: Await is a reserved word. – mixdev Aug 10 '17 at 07:38
  • 4
    Add 'async' keyword to the function definition of the function using 'await' – Vivek Khurana Aug 12 '17 at 06:19
  • Where to call this on page load? – Dhrupal Nov 27 '17 at 10:39
  • You need to call it inside an async function – dan-klasson Jan 21 '18 at 12:02
  • 3
    I am also doing the same with await. After `var value = await AsyncStorage.getItem(STORAGE_KEY);` nothing is happening. Its not returning anything. – Sadhu Apr 18 '18 at 11:02
  • It is not returning anything because of [this](https://github.com/facebook/react-native/issues/12830) and [this](https://github.com/facebook/react-native/issues/14101). – Rafa Viotti Apr 20 '18 at 00:17
  • 1
    For an example below: myfunction = async () => { try { let value = AsyncStorage.getItem(STORAGE_KEY); } } But, I'm getting this error: { [TypeError: undefined is not an object (evaluating '_asyncStorage.AsyncStorage.getItem')] How do we fix this? – naveenkumarbv Apr 26 '19 at 05:31
  • `TypeError: bundle.added is undefined` – Ren Apr 29 '19 at 20:18
  • 1
    Was able to fix this issue. Remove curly braces from the import statement of AsyncStorage and it works. But, it's really weird. `import { AsyncStorage } from '@react-native-community/async-storage';` - doesn't work. But `import AsyncStorage from '@react-native-community/async-storage';` - works fine – naveenkumarbv Apr 30 '19 at 03:23
6

try this option and you will not get the

Syntax Error: Await is a reserved word

async getData() {
    return await AsyncStorage.getItem("@App:KEY");
}
Gal Zalait
  • 61
  • 1
  • 2
0

You can try this:

async getPhoneNumber() {
  const phoneNumber = await AsyncStorage.getItem("phoneNumber")
  console.log(phoneNumber)
}