Home > other >  Asynchronous JS: Button needs to be pressed twice to execute onClick(). The onClick() triggers 2 fun
Asynchronous JS: Button needs to be pressed twice to execute onClick(). The onClick() triggers 2 fun

Time:03-29

I have an issue regarding an application that I am working on. I have a button that is triggering 2 function. One of them is a setState which changes the direction of a dagre graph and the other one is a function that React-flow-renderer provides and fits (centers) the instance of the graph in the screen. I think it needs to be done asynchronously, as the 2nd function is executed only if I double click the button or if I set a setTimeOut to execute after f.ex., 3 seconds. So this works:

<Button
  onClick={() => {
    onChangeTreeLayout('LR');
    setTimeout(() => {
      reactFlowInstance.fitView();
    }, 5000);
  }}
>

This works after the button is pressed for a 2nd time:

<Button
  onClick={() => {
    onChangeTreeLayout('LR');
    reactFlowInstance.fitView();
  }}
>

So I was thinking of doing something like the following, so that the 2nd function will execute as soon as the first is completed: But it returns TypeError: undefined is not an object (evaluating 'a("LR").then')

<Button
  onClick={() => {
    onChangeTreeLayout('LR').then(() => reactFlowInstance.fitView());
  }}
>

Can I please get some help to implement the last one and resolve the error or any other way to wait for the onChangeTreeLayout to be executed and then the reactFlowInstance.fitView() to be triggered as soon as the first is done?

CodePudding user response:

Try using async/await:

<Button
  onClick={async () => {
    await onChangeTreeLayout('LR');
    reactFlowInstance.fitView();
}}
  • Related