Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda