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

296
Visualizações
do React onclick need async/await?

lets say this is what we have:

onClick={() => restrictOrders()}>

and this is our async function

const restrictOrders = async () => {
  try {
    const result = await axios.post(`${config.dev_server}/something`);
    
  }catch(e){}
}

do I need to change the onClick to

onClick={async() => await restrictOrders()}>

the results is the same, I've tested it in both production and local, with high and low internet speed, added long timeouts on the server and in all cases it seems to be waiting for the response.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Short answer - no, it makes no difference.

In general, an await basically means "wait for this Promise to resolve before continuing with the rest of the code". But this means an await before the final statement of a function has no effect whatsoever, because there is nothing that needs to happen after the "wait".

As a simple illustration:

const sleep = (delay) => new Promise(resolve => setTimeout(resolve, delay));

const myFunction = async () => {
  console.log("before");
  await sleep(2000);
  console.log("after");
};

myFunction();

and, as you would no doubt expect, there is a 2 second delay between the "before" and "after".

But if you didn't care about the "after", then you don't need the await at all:

const sleep = (delay) => new Promise(resolve => setTimeout(resolve, delay));

const myFunction = async () => {
  console.log("before");
  sleep(2000);
};

myFunction();

You could use await here, and maybe it's better practice in case you later want to add something after - but there's absolutely no need for it. (In this trivial case of course there's no need to have the sleep call at all - but imagine it's a "real" function with a side-effect, like posting to an API.)

It's the same with your React example:

onClick={async() => await restrictOrders()}>

you are awaiting the last (and in this case, only) statement of an anonymous function. Since there's nothing you do afterwards that needs to wait, there's no harm in not having the await there - so most commonly it's not done, I guess to make the inline function expression less verbose.

about 4 years ago · Juan Pablo Isaza Relatório

0

What has been observed (by me) on some of the apps is this:

Actions taken by the user (such as button-click) result in updating the state. So, in this case, if we have a state-variable like this:

const [ordersRestricted, setOrdersRestricted] = useState(0);

then, the click-handler is like so:

onClick={() => setOrdersRestricted(prev => (prev + 1))}>

Consequently, the corresponding effect (or side-effect) from the action is handled like so:

useEffect(() => {
  const restrictOrders = async () => {
    try {
      const result = await axios.post(`${config.dev_server}/something`);
      // do something with the result
      // typically, update the state (but take care to not change 
      // dependencies, that may lead to infinite looping)
    } catch(e){}
  };
  restrictOrders();
}, [ordersRestricted]);
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