[英]Setting a Loader on API Call "POST"
When a user fills in the input fields and submits a POST method is run.. I would like to show the user that something is happening.当用户填写输入字段并提交时,运行POST方法。我想向用户展示正在发生的事情。 A loader, or spinner, or text just that they do not wait guessing something is happening.
加载器、微调器或文本只是他们不等待猜测正在发生的事情。
I have a solution to that and it works.我有一个解决方案,它有效。 My challenge is only displaying the Loader/Spinner/LoadingText when the
<input/>
fields are not empty and secondly.我的挑战是仅在
<input/>
字段不为空时显示Loader/Spinner/LoadingText ,其次。 I would like the spinner to be false when it gets a response from the API .我希望微调器在从API获得响应时为假。
How can I do that ?我怎样才能做到这一点 ?
Below I have my solution:下面我有我的解决方案:
const [spinner, setSpinner] = useState(false);
const handleSubmit = async () => {
setSpinner(true);
if (!formRef.current?.reportValidity()) {
return;
}
// You'll probably want to invalidate this token and create a new one
const token = process.env.React_App_Sandbox_Api;
const data = {
transactionReference: "string",
paymentMethod: "CreditCard",
checkoutOrderUrl: "http://localhost:3000/transaction",
user: {
name,
msisdn: phone,
email: email,
},
payementMethodDetail: {
RedirectUrl: "http://localhost:3000/transaction",
PurchaseEventWebhookUrl: "http://www.test.com",
},
bundle: cart.map((item) => ({
ProductCode: `${item.ProductCode}`,
Amount: item.amount,
CurrencyCode: item.currencyCode,
Quantity: item.quantity,
})),
};
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(data),
};
try {
const res = await fetch("https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/checkout/",
requestOptions
);
if (!res.ok) {
// some basic handling to come here
return;
}
setResponse(await res.json());
navigate("/payment");
}
finally {
setSpinner(false);
}
return (
<>
<form>
{/* some input fields logic are here */}
</form>
{spinner && <p>something is loading</p>}
<button type="submit" onClick={handleSubmit}>Submit</button>
</>
);
First of all, For handling form data (such as validation), I suggest to use library like react-hook-form.首先,对于处理表单数据(例如验证),我建议使用 react-hook-form 之类的库。 Otherwise you can check input's value if it's empty then return false and setError.
否则,您可以检查输入的值是否为空,然后返回 false 和 setError。 if there is no error, call the API.
如果没有错误,调用 API。 When response received, set spinner false.
收到响应后,将微调器设置为 false。
if (input empty condition) {
setError('fill input');
return false;
}
setSpinner(true);
try {
// API call
setSpinner(false);
} catch (error) {
setSpinner(false);
setError(error);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.