In my Next.js application, I am facing an issue with the sign-up form.
The problem occurs when the user clicks the "sign up" submit button multiple times quickly, resulting in the application sending out multiple fetch requests and displaying multiple toasts on the interface.
What I want is for the user to be unable to take any actions after clicking submit until the first submission is completed.
Initially, I thought about making the API call synchronous. However, it seems that this approach is not recommended:
- You can refer to this answer which advises against using synchronous fetch: How to make javascript fetch synchronous?
I have looked into similar questions but couldn't find a solution that worked:
- For example, check out How to prevent form from submitting multiple times from client side?. The top answer doesn't work well with form validation and relies on JQuery.
I'm still unclear why a synchronous request is not recommended in this scenario. My goal is to stop any activity on the page until the form submission is complete.
Can you suggest the best way to prevent switch bounce during form submission and explain why?
Here is the code snippet for the sign-up page (src/pages/auth/sign-up.js):
const onSubmit = async (data) => {
const { email, password1, password2, first_name, last_name } = data;
const response = await postSignUp( email, password1, password2, first_name, last_name );
// error handling code
toast.success('You have successfully registered!', { autoClose: 2500 })
setTimeout( () => {
router.push({ pathname: '/auth/verify-email', query: { email: email } });
}, 2500 )
API call function (src/lib/api.js):
export async function postSignUp(email, password1, password2, first_name, last_name) {
const response = await fetch(SIGN_UP_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify( { email, password1, password2, first_name, last_name } ),
});
const json = await response.json();
return json;
}