简体   繁体   中英

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

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, eg

.catch((error) => {
   console.log(error.message);
   setMessage("Something went wrong, please contact support");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM