Search code examples
javascriptasync-awaitreact-nativeasyncstorage

AsyncStorage returns unexpected error


Please forgive me if this question is caused by syntax error or of the sort, I'm new to React-Native and there is still many to learn.

I followed the docs and tried out AsyncStorage but it returns an error.

class iCare extends Component {

constructor(props) {
super(props);

async getUserStatus(key){
  try{
    var value = await AsyncStorage.getItem(key);
    if (value == null || value == 0){
      console.log('No loggedIn key yet.');
      loggedIn: false;
    } else {
      console.log('loggedIn key existed');
      loggedIn: true;
    }
  }catch(error){
    console.log('caught error' + error);
  }
}
}

The error says something is wrong with AsyncStorage, but why? Screenshot

Just for the knowledge, is it wise to do AsyncOperation in a constructor method?


Solution

  • It is late, but try this:

    constructor(props) {
      super(props);
    }
    
    async getUserStatus(key){
      try{
        var value = await AsyncStorage.getItem(key);
        if (value == null || value == 0){
          console.log('No loggedIn key yet.');
          loggedIn = false;
        } else {
          console.log('loggedIn key existed');
          loggedIn = true;
        }
      }catch(error){
        console.log('caught error' + error);
      }
    }