javascript - ReactJS ajax response errors rendering in component -
i want render json response errors after ajax call in 'formerror' component.
my error component looks 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 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 errors in 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 errors
{"email":["email exists."],"password":["this field may not blank."]}
but haven't idea how can append errors code , react component.
have separate state variable errors , every time json response contains errors, update variable. then, instance, show details user using condition (having errors empty array if there no errors):
{this.state.errors.length != 0 && ... // traverse them , show details
Comments
Post a Comment