Search code examples
iosfacebookreactjsreact-nativeasyncstorage

How to properly getItem with AsyncStorage in React Native?


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);

Solution

  • 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.