Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot retrieve data from AssyncStorage

I am using the AssyncStorage package from @react-native-community/async-storage and having a big problem when retrieving the stored data.

I don't know how to parse these Promisse results.

The fun fact is that if I console.log(value) inside the if statement, it shows the correct text, but it is returning the Promisse.

This is my function:

const getData = async (key: string) => {
    try {
      const value = await AsyncStorage.getItem(key)

      if(value !== null) {
        return value
      }
    } catch(e) {
      TriggerAlert(I18n.t('error.readError') + e)
    }
  }

This is how I am calling the function

console.log(getData('@key'))

This is the output that I'm getting:

Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}
like image 910
andrecreppe Avatar asked Feb 19 '26 20:02

andrecreppe


1 Answers

The below is correct, the way you extract the data :

const getData = async (key: string) => {
    try {
      const value = await AsyncStorage.getItem(key)

      if(value !== null) {
        return value
      }
    } catch(e) {
      TriggerAlert(I18n.t('error.readError') + e)
    }
  }

Only thing you want to change is the function call place, since getData is an async func , it will return promise , hence you want to wait until the promises either resolves or rejects.

So you can do via ,

let myFunction = async() => {

  console.log(await getData('@key'))
}

hope it helps. feel free for doubts

like image 197
Gaurav Roy Avatar answered Feb 22 '26 11:02

Gaurav Roy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!