Ad

Function Undefined In Axios Promise

- 1 answer

I have the following problem using ReactJs and Axios in an asp.net mvc app

var ForgotPasswordForm = React.createClass({
baseUrl:  "http://localhost:28804/",

getInitialState : function(){
    return{isDisabled:false, text: 'Email Password Reset Link', errorText:''}
},

changeText : function(newText){
    this.setState({text:newText})
},

resetText : function(){
    this.setState({text: "Reset Password"})
},

setErrorText : function(error)
{
    this.setState({errorText:error})
},

enableButton: function(){
    this.setState({isDisabled:true});
},

disableButton: function(){
    this.setState({isDisabled:false});
},

handleSubmit: function(e){
    e.preventDefault();
    var email = this.refs.Email.getDOMNode().value.trim();
    if(!email)
    {  //TODO Show some sort of error message
        this.resetText();
        return;
    }
    var d = new FormData();
    d.append('Email', email);
    this.changeText('Please wait...');
    this.disableButton();
    console.log(d);
    var instance = axios.create({
        baseURL: this.baseUrl
    });
    instance.post('/Account/Login', d)
        .then(function(response){
            console.log(response);
            //I do not have a problem here
        }).catch(function(response){
           //this is where i always have an issue
         console.log(response);
         this.enableButton();
         this.resetText();
    });
    return;
},

render: function(){
    return (
        <form className="form-horizontal"   role="form" onSubmit={this.handleSubmit}>
           //Omitted for brevity
        </form>
    );
}
});
   ReactDOM.render(<ForgotPasswordForm/>, document.getElementById('form-fgt-pwd'));

The problem is when the request fails (500 Internal Server Error on purpose), I get the following output in browser console

TypeError: this.enableButton is not a function

Please what Am i doing wrong

Thanks in advance

Ad

Answer

In .catch function this refers to global scope (in browser it is window), where there is not methods enableButton, resetText, these methods are part of ForgotPasswordForm object, you need set this for catch callback, you can do it with .bind method

.catch(function(response){
   this.enableButton();
   this.resetText();
}.bind(this)); // set this for callback that refers to ForgotPasswordForm Object
Ad
source: stackoverflow.com
Ad