How to properly getItem with AsyncStorage in React Native?

旧时模样 提交于 2020-08-07 07:07:23

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/39657584/how-to-properly-getitem-with-asyncstorage-in-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!