Home > Software engineering >  How to set conditional onClick behaviour in react with async function
How to set conditional onClick behaviour in react with async function

Time:01-28

I have a button which sends an async request but I only want to send this if a variable is false. I have tried to follow this question but I keep getting errors

This is the original onClick

            onClick={async () => {
              const CompleteCA = async () => {
                try {
                  // If status is draft, call sendTransaction
                  if (!statusFinal) {
                    await sendTransaction({
                      variables: {
                        input: {
                          CAId: CA.id,
                        },
                      },
                    });
                  }

                  await updateCA({
                    variables: {
                      id: CA,
                    },
                  });

                  history.push('/');
                } catch (error) {
                  logError(error);
                }
              };
              CompleteCA();
            }}

After adding conditional:

 onClick={async () => {
                  testFlag ? alert("flag is true") :
                  const CompleteCA = async () => {
                    try {
                    ...... rest of function
                    }
                  };
                  CompleteCA();
                }}

I'm getting all the lines underlined since const can't be declared inside onClick, but I'm not sure how to move this out to another function and keep the async intact

CodePudding user response:

I would recommend defining the async function separately and putting the conditional logic in there. Then call it from the onClick like <button onClick={async () => { await asyncFunc(); } }>Click</button>

Here is a simple CodeSandbox example.

  •  Tags:  
  • Related