Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call two function in onchange using Formik

Tags:

reactjs

formik

Problem:

I have select input in my Formik form in react. My code is following

<select
    className="form-control offence-select"
    id="exampleFormControlSelect1"
    value={props.values.offenceId}
    onChange={props.handleChange("offenceId")}
    onBlur={props.handleBlur("offenceId")}
 >
     <option value={0}>Select Offence</option>
         {this.renderOption()}
 </select>

What I want is I want to call two functions inside onChange , one function is formik props.handleChange and the next one is custom state update.

I did something like this.

onChange={e=>{props.handleChange("offenceId");this.handleOffence(props.values.offenceId)}}

But it only calls the second custom function but it is not changing the field value of the select. I tried a lot to find out a solution to this problem but I was unable to do so. Can someone help me to solve this issue by correcting the way I am calling function? Thank you.

like image 894
Tharindu Sandaruwan Avatar asked Dec 17 '22 13:12

Tharindu Sandaruwan


1 Answers

You'll have to pass the event too, otherwise your callbacks do not know what the new value is. I also wouldn't count on props.values having the new value immediately, that's why I would pass the value from event in the second function call.

<select
    className="form-control offence-select"
    id="exampleFormControlSelect1"
    value={props.values.offenceId}
    onChange={(e) => {
      props.handleChange("offenceId")(e);
      this.handleOffence(e.currentTarget.value);
    }}
    onBlur={props.handleBlur("offenceId")}
 >
     <option value={0}>Select Offence</option>
         {this.renderOption()}
 </select>

You could also give your select input a name as follows, which simplifies the callback calls:

<select
    name="offenceId"
    className="form-control offence-select"
    id="exampleFormControlSelect1"
    value={props.values.offenceId}
    onChange={(e) => {
      props.handleChange(e);
      this.handleOffence(e.currentTarget.value);
    }}
    onBlur={props.handleBlur}
 >
     <option value={0}>Select Offence</option>
         {this.renderOption()}
 </select>
like image 133
BerndS Avatar answered Jan 13 '23 15:01

BerndS