0
votes

I am trying to fetch data using AsyncStorage. whenever i call my action creator requestData and do console on the data which is passed , i get something like below .I have two version of getItem .In both the version i get useless value for property field . Property value should be readable

{"fromDate":"20160601","toDate":"20160701","property":{"_40":0,"_65":0,"_55":null,"_72":null},"url":"/abc/abc/xyz"}

 async getItem(item) {
  let response = await AsyncStorage.getItem(item);
  let responseJson = await JSON.stringify(response);
  return responseJson;
}


async getItem(item) {
  try {
    const value =  AsyncStorage.getItem(item).then((value) => { console.log("inside componentWillMount method call and value is "+value);
    this.setState({'assetIdList': value});
     }).then(res => {
    return res;
  });
    console.log("----------------------------value--------------------------------------"+value);
    return value;
  } catch (error) {
    // Handle errors here
    console.log("error is "+error);
  }
}

componentWillMount() {
    requestData({
      fromDate: '20160601',
      toDate: '20160701',
      assetId: this.getItem(cmn.settings.property),
      url: '/abc/abc/xyz'
    });
  }
2

2 Answers

0
votes

You are getting property as a promise, you need to resolve it. Try to use something link that.

 assetId: this.getItem(cmn.settings.property).then((res) => res)
          .catch((error) => null);
0
votes

Since AsyncStorage is asynchronous in nature you'll have to wait for it to return the object AND THEN call your requestData method; something like the following -

class MyComponent extends React.Component {
  componentWillMount() {
    this.retrieveFromStorageAndRequestData();  
  }      

  async getItem(item) {
    let response = await AsyncStorage.getItem(item);
    // don't need await here since JSON.stringify is synchronous
    let responseJson = JSON.stringify(response); 
    return responseJson;
  }

  async retrieveFromStorageAndRequestData = () => {
    let assetId = await getItem(cmn.settings.property);  
    requestData({
      fromDate: '20160601',
      toDate: '20160701',
      assetId,
      url: '/abc/abc/xyz'
    }) ;
  }

  // rest of the component

  render() {
    // render logic
  }
}