S.M_Emamian
S.M_Emamian

Reputation: 17383

AsyncStorage return [object object] - react native

I want to use AsyncStorage but it returns [object object]:

Phone.js component:

        commonHelper.setData("commonConstants.KEY_CODE",'code');

             this.goTo('Activation');

Activation.js component:

   const code = commonHelper.getData("commonConstants.KEY_CODE")
   this.setState({searchString:code.toString()})

commonHelper.js:

function getData(key) {
  try {
       const value = AsyncStorage.getItem(key).then(val => {
         return JSON.parse(val)
       });
       return value
     } catch (err) {
       throw err
     }
}

function setData(key,value) {
  try {
    AsyncStorage.setItem(key, JSON.stringify(value));
  } catch (error) {
    console.log("Error saving data" + error);
  }
}

where is my problem?

Upvotes: 0

Views: 1199

Answers (1)

Jeremy
Jeremy

Reputation: 3728

AsyncStorage is returning a promise. your getData returns that promise.

to read the data, you need to use a .then

commonHelper.getData("commonConstants.KEY_CODE")
    .then(code => {
        this.setState({searchString:code}) // or code.toString().. depends on what you stored
    });`

Also, the return value in your getData function is necessary because you are returning the promise in .then

Upvotes: 2

Related Questions