Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
How to set conditional onClick behaviour in react with async function

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 (!statusFinal) {
                    await sendTransaction({
                      },
                    });
                  }

                  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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!