I am using API to extract data from Amazon API and I am using react js for it.

The problem is when I extract them and save it in the state it gives me an error of undefined, however, I am getting the result from the API. The function takes time to get data from API, I am using a method of extracting data which is suitable in node js but also working in react and I am getting a result, but unable to save it in a state. Here's the code below:

    let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;

    mws.request(getReport, function(e, result) {
        temp=result;
        this.setState({amazon_data:result})  // gives undefined error
    });

I think the reason is the function execution takes time and it runs the setstate line which makes the result null, any suggestions on how to fix this?

1 Answers

2
coderocket On Best Solutions

That happens because this.setState is not part of the this scope inside your function.

 let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;
    const _this = this;
    mws.request(getReport, function(e, result) {
        temp=result;
        _this.setState({amazon_data:result})  // this works because _this references the outer this
    });

That should work or you can use arrow functions like below.

 let getReport={
        path:'/',
        query:{
            Action:'GetReport',
            ReportId:'14941942615018036',
            Version:'2009-01-01',
        }
    };

    let temp=null;

    mws.request(getReport, (e, result) => {
        temp=result;
        this.setState({amazon_data:result})  // this works because the arrow function binds the outer this to the function
    });