Home > Software design >  Javascript promises catch block initiating when no error
Javascript promises catch block initiating when no error

Time:12-22

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")
      );
  }

CodePudding user response:

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");
});
  • Related