ReactJS ajax response errors rendering in component

By : Robson
Source: Stackoverflow.com
Question!

I want to render my json response errors after ajax call in my 'FormError' component.

My error component looks like this:

var FormError = React.createClass({
    render: function () {
        return (
            <span className="form-error"></span>
        );
    }
});

My form:

var EmailForm = React.createClass({
    getInitialState: function(){
      return {
          password:'',
          email: ''
      };
    },

    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
      })
      .done(function(data) {
        toastr.success('Profile updated');
      })
      .fail(function(jqXhr) {
        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}/>
                    <FormError/>
                </div>
                <div className="form-half">
                    <label htmlFor="lastname" className="input-label">New email</label>
                    <BasicInput valChange={this.emailChange} val={this.state.email}/>
                    <FormError/>
                </div>
                 <button type="submit" className="button secondary" >Submit</button>
            </form>
        );
    }
});

This code works, ajax call give me response json with errors

{"email":["Email already exists."],"password":["This field may not be blank."]}

but I haven't idea how can I append this errors to my code and my react component.

By : Robson


Answers

Why not just set an error state?!

Could something like this:

var EmailForm = React.createClass({
constructor(props) {
  this.onError = this.onError.bind(this);
}

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

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) 
By : Inoir


Have a separate state variable for errors and every time the json response contains errors, update the variable. Then, for instance, you could show the details to user using this condition (having errors as an empty array if there are no errors):

{this.state.errors.length != 0 
By : Igorsvee


This video can help you solving your question :)
By: admin