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

94
Visualizações
Javascript promises catch block initiating when no error

I have created a function that makes a call to an api shown below. I am displaying the message from setMessage on the front end. For some reason when there is no error the .catch block message flashes in setMessage() and then the setMessage() finally ends with the correct message from .then().

I'm not sure why this is.

function handleCoupon(e) {
    e.preventDefault();
    setMessage("");
    setLoading(true);
    fetch(`${process.env.NEXT_PUBLIC_SERVER_API}/subscription/coupon/get`, {
      method: "POST",
      body: JSON.stringify({
        appliedCoupon: couponCode.toLowerCase().trim(),
      }),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        if (data.coupon === true) {
          setMessage(data.message);
          setLoading(false);
        } else {
          setMessage(data.message);
          setLoading(false);
        }
      })
      .catch(
        (error) => console.log(error.message),
        setMessage("Something went wrong, please contact support")
      );
  }
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The .catch only accept single function as parameter, and you are passing 2 of them:

  1. (error) => console.log(error.message)
  2. setMessage("Something went wrong, please contact support")

Try merging them into 1 function, e.g.

.catch((error) => {
   console.log(error.message);
   setMessage("Something went wrong, please contact support");
});
about 4 years ago · Santiago Trujillo 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