我创建了一个函数,可以调用如下所示的api。我正在前端显示来自setMessage的消息。由于某种原因,当没有错误时。catch block消息在setMessage()中闪烁,然后setMessage()最后以来自的正确消息结束。然后()。
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")
);
}