How to properly getItem with AsyncStorage in React Native?

Ega Setya Putra picture Ega Setya Putra · Sep 23, 2016 · Viewed 7.8k times · Source

My current project require me to store user data locally, So I use the AsyncStorage from react native itself. However I got some issues on how to retrieve already saved data I always get null but somehow the data is saved..

I always get

{ _45: 0, _81: 0, _65: null, _54: null }

and here's my code, which is the simple example from react native documentation

AsyncStorage.setItem('baru', 'this is new dude!!');
var b = AsyncStorage.getItem('baru');
console.log(b);

Answer

Ferran Negre picture Ferran Negre · Sep 23, 2016

Reading the docs of AsyncStorage:

static getItem(key, callback?) Fetches an item for a key and invokes a callback upon completion. Returns a Promise object.

You need to handle that promise. I'd recommend you to use (as the docs) async/await. So for example you can do:

async function getItem(item) {
  try {
    const value = await AsyncStorage.getItem(item);
    console.log(value);
    return value;
  } catch (error) {
    // Handle errors here
  }
}

You should actually do something similar for setItem too.