1

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.

2 Answers 2

1

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 && ... // traverse them and show details
Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, I don't think so I understand you well. I created state errors, but how update state variable into ajax call error ?
Inspect the response that comes from the server and if it contains errors call setState to update the state of your compoent. You are already doing the same thing with email
0

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) && !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) {
    self.onError(jqXhr.response);
    toastr.error('There is some errors in your request');
  });

},

onError: function(response) {
  this.setState({
   passwordError: response.password,
   emailError: response.email
  })
}

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

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

render: function() {
   const {emailError, passwordError} = this.state;

    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}/>
                {emailError && <FormError error={emailError}/>}
            </div>
            <div className="form-half">
                <label htmlFor="lastname" className="input-label">New email</label>
                <BasicInput valChange={this.emailChange} val={this.state.email}/>
                {passwordError && <FormError error={passwordError}/>}
            </div>
             <button type="submit" className="button secondary" >Submit</button>
        </form>
    );
}
});

Its a bit simplified..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.