Ankzious
Ankzious

Reputation: 325

Call multiple functions onChange event -- React

I have a React component of Dropdown list.

When any of the list item selects, 2 functions needs to be called, which respectively do 2 things:

  1. The value should be posted in a API
  2. Also some other actions dependent of the Dropdown option select.

I tried both the functions one-by-one in the "onChange" handler, they works fine individually but when calling together, it messed up things.

My code until here looks like this:

  handleChange(e) {
    e.preventDefault();
    console.log("this is target's value: "+ e.target.value)
    this.setState({value: e.target.value})
    let fd = new FormData();
    
    fd.append("value", e.target.value);
    axios({
      method: 'post',
      url: `${api}/project/role`,
      data: fd,
      })
      .then((data) => {
        console.log(this.state)
      })

Render component as:

render() {
...
...
        <><div style={{height:'7px'}}>Select from options:</div><br/>
        <select value={this.props.role.prefer} onChange={(e) => this.props.selectedRoleAction(e.target.value)} className="form-control">  //The function placed right now in onChange is a action reducer function.

...
...
}

Now in onChange I want to call handleChange as well to POST value in API. How can I achieve this? Appreciate any help!

Upvotes: 1

Views: 7530

Answers (1)

Ankzious
Ankzious

Reputation: 325

To summarize the solution discussed in comment section:

Calling 2(or many more functions) simply make (e) => {thing1();thing2()} as Charles suggested.

The answer to the problem above, which worked as suggested by David. And on how to call 2 functions for the above problem is by taking the event for both the functions like:

        <select value={this.state.value} onChange={(e) => this.props.selectedRoleAction(e.target.value) ; this.handleChange(e)} className="form-control"> 

Thanks guys for guidance. Appreciate the help!

Upvotes: 1

Related Questions