MemoryLeak MemoryLeak - 3 days ago 5
React JSX Question

TypeError: this.updateUserList is not a function. reactjs

handleAddUser(){
if(this.checkRequiredField()){
$.ajax({
url:this.state.location,
datatype:'text',
type:'POST',
data:{
UserId:this.state.userId,
AccountName:this.state.accountName
},
success:function(data,statuc,xhr){
console.log(xhr.getResponseHeader('Location'));
console.log('data added successfully');
this.updateUserList(xhr.getResponseHeader('Location'));
},
error:function(xhr,status,err){
console.error(status, err.toString());
}
});
}
}


In the above post request, it's success function has a method to update the userlist.

updateUserList method is defined and has mentioned in the constructor like this

this.updateUserList = this.updateUserList.bind(this);


but the method is not being executed, instead I got the below error in the browser console

TypeError: this.updateUserList is not a function
.

I do have a similar code in another screen, which works as expected.
How to fix this issue?

Answer

You need to bind the success function of ajax cal. The problem occurs because you are calling the updateUserList function as this.updateUserList, however this inside the success call doesn't refer to outer scope but the scope of the success call

handleAddUser(){
    if(this.checkRequiredField()){
        $.ajax({
            url:this.state.location,
            datatype:'text',
            type:'POST',
            data:{
                UserId:this.state.userId,
                AccountName:this.state.accountName
            },
            success:function(data,statuc,xhr){
                console.log(xhr.getResponseHeader('Location'));
                console.log('data added successfully');                 
                this.updateUserList(xhr.getResponseHeader('Location'));                 
            }.bind(this),
            error:function(xhr,status,err){
                console.error(status, err.toString());
            }.bind(this)
        });
    }
}
Comments