Search code examples
javascriptreactjscallbacksetstate

In call back Function getting state error?


Initially I have state variable url: ''

let data = this.state.content;
    ContractAction._generatePDF(data, function(data){
        let filename = data.filename;
        let accesstoken = localStorage.getItem('accessToken');
        this.setState({url : "http://172.104.16.14:1082/contracts/downloadpdf?filename=" + filename + "&access_token=" +accesstoken });

    });

And after API call, In callback I am trying to set the url state to the url given but it is not updating

I am facing an error of State Cannot read property 'state' of undefined.

I want the url state to be changed to http://172.104.16.14:1082/contracts/downloadpdf?filename=" + filename + "&access_token=" +accesstoken


Solution

  • Because this has scope problem.

    The reason why you get setState of undefined because this is undefined inside the callback. As it is currently pointing to the instance of callback not the whole class itself. You should better use Arrow functions that takes care of such matters -

    • You don't need to keep typing function
    • It lexically captures the the meaning of this
    • It lexically captures the meaning of arguments

    do this

    ContractAction._generatePDF(data, (data) => {
            let filename = data.filename;
            let accesstoken = localStorage.getItem('accessToken');
            this.setState({url : "http://172.104.16.14:1082/contracts/downloadpdf?filename=" + filename + "&access_token=" +accesstoken });
        });
    

    or just define it as scope variable

    let data = this.state.content;
    let scope = this;
    

    and use

    scope.setState({url : "http://172.104.16.14:1082/contracts/downloadpdf?filename=" + filename + "&access_token=" +accesstoken });