0

I need to execute 2 functions based on one onClick event. for this, I found some methods Via stackoverflow. (Referred Call multiple functions onClick ReactJS)

But, in my case if I specified as onClick={this.handleClick} works as expected. But if I specified as onClick={(event) => {this.handleClick()}}, when clicking on button nothing happens. What could be the reason for this? What is the optimal way of calling two functions one by one on one onClick where second function call depends on the result of first function call.

Vithursa Mahendrarajah
  • 1,194
  • 2
  • 15
  • 28

3 Answers3

1

In Javascript, this is not defined statically for a piece of code (like in 99% other languages), but rather taken from the calling context (i.e. it is dynamically scoped), so it can differ depending on who calls the function and when.

In the second case, this evaluates late: when the function is called. In the first case, it is evaluated when the event is attached (so it is "correct").

The solution is simply to use the first version - there is nothing you gain by calling it late (the event will be passed anyway, as the first argument).

fdreger
  • 12,264
  • 1
  • 36
  • 42
1

You can try the following

Your onClick goes like this which by default sends an event

onClick={this.handleClick}

handleClick event

handleClick = (event) => {
  fetch.fetchUrl(url [, options], ()=> {
   this.getFoo();
  })
}
getFoo = ()=>{}

Second way

You can send event by binding the function

onClick={this.handleClick.bind(this, additionalParameter)}

now click function would look like

handleClick = (additionParameter, event) =>{}

Additionally, If you would like to send additional parameters alongside you can go with the second way. Both the ways would still pass events attached with your handler.

Manoz
  • 6,507
  • 13
  • 68
  • 114
0

Calling first function inside second should work. PFB the steps -

  1. Define first function.
  2. In second function definition, fist call first function and use the first function output accordingly for further operation statement in second function's definition.
  3. call second function on click event.

This will lead to call second function but will do operation on the basis of the output provided on calling first function.

MadhuriJain
  • 145
  • 2
  • 4