Rafdro
Rafdro

Reputation: 790

React native AsyncStorage bad response

Have created React Native app and ned to use AsyncStorage to benefit from it's storage mechanism.

To save in AsyncStorage use code:

  _storeData = async (param) => {
    try {
      let par = JSON.stringify(param);
      //await AsyncStorage.setItem(this.key, par);
      Utilities.setItem(this.key, par);
      this._retrieveData();
    } catch (error) {
      console.log(JSON.stringify(error));
    }
  };

To retrieve data:

 _retrieveData = async () => {
    try {      
      const value = Utilities.getItem(this.key);
      if (value !== null) {
        alert('data is new: ' + JSON.stringify(value));
      }
    } catch (error) {
    }
  };

And, to setItem and getItem in Utilities partial:

const setItem = (key, value) => {
  if (!key || !value) return;
  AsyncStorage.setItem(key, value);
};

const getItem = (key) => {
  if (!key) return;
  var val = AsyncStorage.getItem(key);
  return val;
};

Data is being saved, but response I'm getting does not look correctly, as it's a string of 'weird' characters:

{"_40":0,"_65":0,"_55":null,"_72":null}

Does anybody know why I'm getting such answer?

Upvotes: 0

Views: 229

Answers (1)

azundo
azundo

Reputation: 6052

Note that AsyncStorage.getItem is also async - the weird characters represent the promise being returned by getItem.

Use var val = await AsyncStorage.getItem(key); and mark your getItem utility function as async. You'll need to await on any calls to Utilities.getItem and Utilities.setItem as well.

Upvotes: 3

Related Questions