0

I need to convert responseJson.result (JSON Object) to data (JS Object).
When I use console log or alert it's return undefined.

I don't know what's wrong - something about console log or alert method or stringify?

constructor() {
  super();
  this.state = {
    data: null,
  };
}

componentWillMount() {
  return fetch("www.abc.xyz/api")
    .then((response) => response.json())
    .then((responseJson) => {
      let ds = new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 !== r2
      });

      this.setState({
        data: JSON.stringify(responseJson.result),
      }, function() {
      });

      var resultJ = this.state.data.result;
      alert(resultJ);
    })
    .catch((error) => {
      alert("0 : Recrods On This Module ")
    });
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
boy_v
  • 547
  • 3
  • 8
  • 23
  • what does `console.log(responseJson)` before you `setState`say? – Nocebo Aug 10 '17 at 14:28
  • datasource from responseJson it's work on listview. but I want to convert responseJson to data and set data on Listview – boy_v Aug 10 '17 at 14:30

1 Answers1

0

The setState call is asynchronous which means the state values are not available immediately. You already have the callback parameter in your setState set. You only need to use it e.g.

this.setState({
    data: JSON.stringify(responseJson.result),
}, function () {
    var resultJ = this.state.data.result;
    alert(resultJ);
});
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107