Stefan Stefan - 1 year ago 68
React JSX Question

ReactJS & Flux get data from promise

I am trying to get data from server with service function that I found in a template reactjs project. I do recieve a perfectly fine anwser from the server, I can see the arrays are ok while still in the service, but not when handed over to the component that called for it in the first place. At the component I get a promise object, which has the values (I have seen them in console) but I can't access them. What am I missing?

My component has following function:

calculate(dict) {
var results = Service.calc(dict)
.catch((err) => {
var errResp = JSON.parse(err.response);
console.log(errResp);
this.setState({responseErrors: errResp});
});
this.setState({results:results._handler});
}


When I printed the results in to console I saw the Promise object, inside _handler.handler was a value array with my values but I couldn't use them. The error appeared when accessing the results._handler.handler: undefined.

The called service looks like this:

class Service {
calc(dict) {
return this.handleCalculate(when(request({
url: UserConstants.URL,
method: 'POST',
type: 'json',
data: dict
})));
}

handleCalculate(calcPromise) {
return calcPromise.then(
function(data) {
console.log(data); //Success
return data;
}
)
}


Meanwhile I use ajax call directly in the component instead of the service. But I understand that is bad practice, how can I get this right?

Answer Source

Hi basically you put setState in the wrong place. (It sets state right away without waiting for result getting resolved). It should look like this

calculate(dict) {
    var results = Service.calc(dict)
      .then(results => {
         this.setState({results: results});
      })
      .catch((err) => {
          var errResp = JSON.parse(err.response);
          console.log(errResp);
          this.setState({responseErrors: errResp});
    });
}