-1

I've read several stackoverflow questions and answers about this matter and none of them seem to solve my problem.

I am using Async/await functions in a react native app and I'm trying to access data from AsyncStorage. I am trying to get a value using .getItem and then use it outside the async function. This is the function I'm using to get the data.

async _getStorageValue(){
  var value = await AsyncStorage.getItem('ITEM_NAME')
  return value
}

However, when I call this function and set it to a variable, like this:

returnedValue = _getStorageValue()

A promise is returned:

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
}

How do I access the value inside this async function without using the useState hook?

  • `let value; _getStorageValue().then(v => value = v)` would be how to do that (declare a global, fill it when the promise is resolved). However, code that relies on that global being filled might fail in the meanwhile, so best to wrap your code in an `async function` and do `const value = await _getStorageValue();`, which will pause execution of that code until the value is resolved. – somethinghere Aug 21 '21 at 19:44
  • 1
    _"without using the useState hook"_ - are you using class based components? If not, then no you cannot use the value from an async function without the `useState` hook. – evolutionxbox Aug 21 '21 at 19:44

2 Answers2

2

Change your Global Function to

_getStorageValue(){
  return AsyncStorage.getItem('ITEM_NAME')
}

and make async call while storing

returnedValue = await _getStorageValue()
FnH
  • 587
  • 4
  • 5
0

I'm not completely sure about it but I think you want this:

    async _getStorageValue(){
     var value = await AsyncStorage.getItem('ITEM_NAME').then((val) => val)
    }

The then keyword makes sure to wait for the promise to resolve. Note: The promise can also fail, I'm not sure how to handle that as of this moment.

Julianvv
  • 100
  • 10