Robson Robson - 3 months ago 20
React JSX Question

reactjs update state after ajax call

I want to update my state when I get errors from my ajax call.

My code:

var EmailForm = React.createClass({

getInitialState: function(){
return {
password:'',
email: '',
errors: ''
};
},

componentDidMount: function() {
this.serverRequest = $.get('/accounts/email-form/', function (result) {
var userInfo = result;
this.setState({
email: userInfo.email
});
}.bind(this));
},

submit: function (e){
var self;

e.preventDefault()
self = this;

console.log(this.state);

var data = {
password: this.state.password,
email: this.state.email,
CSRF: csrftoken
};

// Submit form via jQuery/AJAX
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({
type: 'POST',
url: '/accounts/email-form/',
data: data,
datatype: JSON
})
.done(function(data) {
toastr.success('Profile updated');
})
.error(function(jqXhr) {
var error = jqXhr.responseJSON; //How can I append this errors to my errors state ?
toastr.error('There is some errors in your request');
});
},

passwordChange: function(e){
this.setState({password: e.target.value});
},

emailChange: function(e){
this.setState({email: e.target.value});
},

render: function() {
return (
<form onSubmit={this.submit}>
<div className="form-half">
<label htmlFor="password" className="input-label">Current Password</label>
<BasicInputPassword valChange={this.passwordChange} val={this.state.password}/>
<span className="form-error is-visible">{this.state.errors.password}</span>
</div>
<div className="form-half">
<label htmlFor="email" className="input-label">New email</label>
<BasicInput valChange={this.emailChange} val={this.state.email}/>
<span className="form-error is-visible">{this.state.errors.email}</span>
</div>
<button type="submit" className="button secondary" >Submit</button>
</form>
);
}
});


I have response errors in error variable. How can I update state errors with this json and display for example state.errors.email easy ? Is this possible ?

Answer

use this.setState()

var that = this;
$.ajax({
        type: 'POST',
        url: '/accounts/email-form/',
        data: data,
        datatype: JSON
      })
      .done(function(data) {
        toastr.success('Profile updated');
      })
      .fail(function(xhr, status, error) {
          that.setState({
          //assign error to whatever you want under `state`
          });
      });

*make sure this is pointing at the right scope. Or use arrow functions for lexical this.

Comments