27

I am trying to call two functions with an onChange event for search functionality dynamically in react. in first function I am setting the state for a value and in second function I have to call the value and execute the function.

I was not able to call two functions at same time. I am not adding the mock JSON with this sample code.

 handleChange(e) {
   this.setState({ value: e.target.value.substr(0, 20) });
}
filterFunction(filteredSections) {
  let search = filteredSections;
  search = filteredSections.filter(somesection => somesection.insidesection && somesection.insidesection.name.toLowerCase().indexOf(this.state.value.toLowerCase()) !== -1);
return search;
    }
 render() {
    const filteredSections = othersection;
return(

<div>
<FormControl
    name="searching"
    placeholder="Searching"
    onChange={e => this.handleChange(e).bind(this)}
    onChange={() => this.filterFunction(filteredSections)}
/>
</div>
<div>
    {filteredSections.map(section =><othersection customization={section} } }
</div>
)
}

the expected should be onchange event has to be call both the functions.

2 Answers 2

52

You can only assign a handler to onChange once. When you use multiple assignments like that, the second one will overwrite the first one.

You will either have to make a handler that calls both functions, or use an anonymous function:

twoCalls = e => {
  this.functionOne(e)
  this.functionTwo()
}
.
.
.
<FormControl
    name="searching"
    placeholder="Searching"
    onChange={this.twoCalls}
/>

Or...

<FormControl
    name="searching"
    placeholder="Searching"
    onChange={e => { this.functionOne(e); this.functionTwo() }}
/>
2
  • 1
    That works like a charm!, if the state is need to be same in both the functions, what is the best practice to update it? as of now it is updating only in first function and in second function after second event happened, it shows first state.
    – sai
    Jan 4, 2019 at 2:47
  • 2
    State is updated asynchronously so it won't have been updated yet at the time the second function is called. You could just pass value to the second function.
    – Herohtar
    Jan 4, 2019 at 3:54
8

if you need props you can use it

<FormControl
    name="searching"
    placeholder="Searching"
    onChange={e => { this.functionOne(e); this.props.functionTwo(e)}
/>

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.