I'm new to react I've to submit the form and after that validation is happening since I've called onclick function it redirects to me as an error so now after validation if is it correct call the save function the below is my code and the save method is create job please help me out to this

export default class PostJob extends Component {

 constructor(props) {
    super(props);

this.state = {
  sectionData: null,
  startdate: moment(),
  enddate: moment()

};

this.startdateChange = this.startdateChange.bind(this);
this.enddateChange = this.enddateChange.bind(this);
this.jobtitleChange = this.jobtitleChange.bind(this);
this.companyChange = this.companyChange.bind(this);
this.salarytypeChange = this.salarytypeChange.bind(this);

}




onCreateJob() {

  var applicants_type = document.getElementById('JOB_applicants_type').value;
  var title = this.state.jobtitle.value;
  var company = this.state.company.value;
  var type = document.getElementById('JOB_type').value;
  var salary = document.getElementById('JOB_salary').value;
  var salarytype = this.state.salarytype.value;
  var location = document.getElementById('JOB_location').value;
  var description = document.getElementById('JOB_description').value;
  var startdate = moment(this.state.startdate).format('YYYY-MM-DD');
  var enddate = moment(this.state.enddate).format('YYYY-MM-DD'); 
  var draft = 'main';

  axios.post(window.mg.api.baseURL + 'createjob', {
    headers: {
      'X-CSRF-TOKEN': window.mg.api.token,
      'Content-Type':'application/x-www-form-urlencoded'
    },
    params: {
      applicants_type: applicants_type,
      title: title,
      company: company,
      type: type,
      salary: salary,
      salarytype: salarytype,
      location: location,
      description: description,
      startdate: startdate,
      enddate: enddate,
      draft: draft
    }

  })
  .then(response => {


    })
      .catch(function(thrown) {
        if (axios.isCancel(thrown)) {
          console.log('Request canceled', thrown.message);
        } else {
          // handle error
            console.log('Error', thrown.message);
        }
      });

}


  render() {

const jobtitle = this.state.jobTitleList;
const company = this.state.companyList;
const salarytype = this.state.salaryTypeList;

const defaultOption = null;

const validations = {
  JOB_applicants_type: ["required"],
  title: ["required"],
  jobtitle: ["required"],
  description: ["required"],
  company: ["required"],
  JOB_type: ["required"],
  salarytype: ["required"],
  JOB_location: ["required"],
  startdate: ["required"],
  enddate: ["required"]
 }



  return (

  <div className="hrs_create_job_container">
  <Formik
  initialValues={{ title: '', company: '',radio: '',salarytype: '',location: '',job_description: '',startdate: '',enddate: '' }}
  validate={values => {
    let errors = {};
    if (!values.title) { 
      errors.title = 'Required';
    } 
    if (!values.company) {
      errors.company = 'Required';
    } 
     if (!values.radio) {
      errors.radio = 'Required';
    } 
      if (!values.salarytype) {
      errors.salarytype = 'Required';
    } 
     if (!values.location) {
      errors.location = 'Required';
    }
    if (!values.job_description) {
      errors.job_description = 'Required';
    }
    if (!values.startdate) {
      errors.startdate = 'Required';
    }
     if (!values.enddate) {
      errors.enddate = 'Required';
    }
    //return errors;
  }}
  onSubmit={(values, { setSubmitting }) => {
    var isValid = true;
    alert(isValid);
    setTimeout(() => {
      alert(JSON.stringify(values, null, 2));
      setSubmitting(false);
    }, 400);
  }}
>
  {({
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
    isSubmitting,
    /* and other goodies */
  }) => (
    <form onSubmit={handleSubmit}>
     <div className="hrs_create_post_top">
      <div className="col-sm-6 hrs_job_top_radio_">
        <div className="hrs_job_top_radio">
          <input type="radio" id="JOB_applicants_type" value={this.state.value} />
          <span className="checkmark"></span>              
        </div>
        <span className="hrs_job_top_radio_text">INTERNAL AND EXTERNAL APPLICANTS</span>            
      </div>
      <div className="col-sm-6 hrs_job_top_radio_">
        <div className="hrs_job_top_radio">
          <input type="radio" value={this.state.value} />
          <span className="checkmark"></span>              
        </div>
        <span className="hrs_job_top_radio_text">INTERNAL APPLICANTS ONLY</span>            
      </div>
    </div>
    <div className="hrs_job_create">
      <label>JOB TITLE</label>
      <Select className="hrs_select" name= "title"  onChange={this.jobtitleChange} onBlur={handleBlur}  options={jobtitle} onChange={this.jobtitleChange} value={this.state.jobtitle} placeholder='TYPE JOB TITLE'/>
    {errors.title && touched.title && errors.title}
    </div>


      <div className="hrs_job_create">
      <label>COMPANY</label>
        <span className="hrs_input"><Select className="hrs_select" name="company" options={company} onChange={this.companyChange} value={this.state.company} placeholder='SELECT COMPANY'/></span>
    {errors.company && touched.company && errors.company}
    </div>

    <div className="hrs_job_create">
     <div className="hrs_job_create">
      <label>TYPE</label>
        <span className="hrs_input"><input type="radio" id="JOB_type" name="JOB_type" value={1} /> PERMANENT
        <input type="radio" id="JOB_type" name="JOB_type" value={0} /> TEMPORARY</span>

    </div>
    {errors.radio && touched.radio && errors.radio}  
    </div>
  <div className="hrs_job_create">
      <label>SALARY</label>
        <span className="hrs_input">
          <span className="hrs_currency">&pound;</span>
          <input type="text" id="JOB_salary"/>
          <Select className="hrs_select hrs_select_salarytype" name="salarytype" options={salarytype} onChange={this.salarytypeChange} value={this.state.salarytype} placeholder='SELECT SALARY TYPE'/>
        </span>
   {errors.salarytype && touched.salarytype && errors.salarytype}
    </div>


      <div className="hrs_job_create">
      <label>LOCATION</label>
      <span className="hrs_input"><input type="text" name="location" id="JOB_location" placeholder="TYPE LOCATION" className="hrs_input_full-length" /></span>
   {errors.location && touched.location && errors.location}
    </div>


     <div className="hrs_job_create hrs_job_description">
      <div className="hrs_job_description_label">
        <label>JOB DESCRIPTION</label>
      </div>
      <span className="hrs_input"><textarea type="text" name="job_description" id="JOB_description" name="description" placeholder="TYPE JOB DESCRIPTION" className="hrs_input_full-length" /></span>          
    {errors.job_description && touched.job_description && errors.job_description}
    </div>

     <div className="hrs_job_create">
      <label>START AND END DATE OF POSTING</label>
      <span className="hrs_input hrs_input_from_to">
        <div className="hrs_datepicker">
          <DatePicker name="startdate" dateFormat="DD MMM YYYY" selected={this.state.startdate} onChange={this.startdateChange}/>
        {errors.startdate && touched.startdate && errors.startdate}
        </div>
        <b>TO</b>
        <div className="hrs_datepicker">
          <DatePicker name="enddate" dateFormat="DD MMM YYYY" selected={this.state.enddate} onChange={this.enddateChange}/>
       {errors.enddate && touched.enddate && errors.enddate}
        </div> 
      </span>
    </div>
     <div className="hrs_create_job_btns">        

      <button className="BTNFilled BTNOutlineFilled">SAVE DRAFT</button>
       <button type="submit" disabled={isSubmitting} className="BTNFilled"  onClick={this.onCreateJob.bind(this)}>POST JOB</button>

    </div>

     {/* <button type="submit" disabled={isSubmitting}>
        Submit
      </button>*/}
    </form>
  )}
</Formik>
    </div>
  );

  var BTNStyle = {};
  BTNStyle.marginRight = "10px";
  BTNStyle.marginLeft = "0px";
  BTNStyle.marginBottom = "30px";

}

}

In this, I followed the Formik validation method but don't know how to do it after validation true call the save method and still no idea on that

1 Answers

0
arpit sharma On Best Solutions

You have to insert whatever your post action is inside this block for instance I put an alert

axios.post(window.mg.api.baseURL + 'createjob', {
....)
  .then(response => {
    //here you have to do whatever action you wist to perform after success
      alert("Form is saved");
   //or you wish to navigate to other page you can put routing or a success dialog box

  })

Instead of calling createJob directly onclick from the button you have to call it in onSubmit method like below

 onSubmit={(values, { setSubmitting }) => {
 setTimeout(() => {
  this.createJob(); // ideally you can pass values in it so that you don't need to extract from the DOM
  alert(JSON.stringify(values, null, 2));
  setSubmitting(false);
}, 1000);
}}