If youāve ever used JavaScriptĀ fetch
Ā API to enhance a form submission, thereās a good chance youāve accidentally introduced a duplicate-request/race-condition bug. Today, Iāll walk you through the issue and my recommendations to avoid it.
(Video at the end if you prefer that)
Letās consider a very basicĀ
<form method="post">
<label for="name">Name</label>
<input id="name" name="name" />
<button>Submit</button>
</form>
When we hit the submit button, the browser will do a whole page refresh.
Notice how the browser reloads after the submit button is clicked.
The page refresh isnāt always the experience we want to offer our users, so a common alternative is to useĀ fetch
Ā API.
A simplistic approach might look like the example below.
After the page (or component) mounts, we grab the form DOM node, add an event listener that constructs aĀ fetch
Ā request using the formĀ preventDefault()
Ā method.
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
function handleSubmit(event) {
const form = event.currentTarget;
fetch(form.action, {
method: form.method,
body: new FormData(form)
});
event.preventDefault();
}
Now, before any JavaScript hotshots start tweeting at me about GET vs. POST and request body andĀ fetch
Ā request deliberately simple because thatās not the main focus.
The key issue here is theĀ event.preventDefault()
. This method prevents the browser from performing the default behavior of loading the new page and submitting the form.
Now, if we look at the screen and hit submit, we can see that the page doesnāt reload, but we do see the HTTP request in our network tab.
Notice the browser does not do a full page reload.
Unfortunately, by using JavaScript to prevent the default behavior, weāve actually introduced a bug that the default browser behavior does not have.
When we use plainĀ
If we compare that to the JavaScript example, we will see that all of the requests are sent, and all of them are complete without any being canceled.
This may be an issue because although each request may take a different amount of time, they could resolve in a different order than they were initiated. This means if we add functionality to the resolution of those requests, we might have some unexpected behavior.
As an example, we could create a variable to increment for each request (ātotalRequestCount
ā). Every time we run theĀ handleSubmit
Ā function, we can increment the total count as well as capture the current number to track the current request (āthisRequestNumber
ā).
When aĀ fetch
Ā request resolves, we can log its corresponding number to the console.
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
let totalRequestCount = 0
function handleSubmit(event) {
totalRequestCount += 1
const thisRequestNumber = totalRequestCount
const form = event.currentTarget;
fetch(form.action, {
method: form.method,
body: new FormData(form)
}).then(() => {
console.log(thisRequestNumber)
})
event.preventDefault();
}
Now, if we smash that submit button a bunch of times, we might see different numbers printed to the console out of order: 2, 3, 1, 4, 5. It depends on the network speed, but I think we can all agree that this is not ideal.
Consider a scenario where a user triggers severalĀ fetch
Ā requests in close succession, and upon completion, your application updates the page with their changes. The user could ultimately see inaccurate information due to requests resolving out of order.
This is a non-issue in the non-JavaScript world because the browser cancels any previous request and loads the page after the most recent request completes, loading the most up-to-date version. But page refreshes are not as sexy.
The good news for JavaScript lovers is that we can have both aĀ
We just need to do a bit more legwork.
If you look at theĀ fetch
Ā API documentation, youāll see that itās possible to abort a fetch using anĀ AbortController
Ā and theĀ signal
Ā property of theĀ fetch
Ā options. It looks something like this:
const controller = new AbortController();
fetch(url, { signal: controller.signal });
By providing theĀ AbortContoller
ās signal to theĀ fetch
Ā request, we can cancel the request any time theĀ AbortContoller
āsĀ abort
Ā method is triggered.
You can see a clearer example in the JavaScript console. Try creating anĀ AbortController
, initiating theĀ fetch
Ā request, then immediately executing theĀ abort
Ā method.
const controller = new AbortController();
fetch('', { signal: controller.signal });
controller.abort()
You should immediately see an exception printed to the console. In Chromium browsers, it should say, āUncaught (in promise) DOMException: The user aborted a request.ā And if you explore the Network tab, you should see a failed request with the Status Text ā(canceled).ā
With that in mind, we can add anĀ AbortController
Ā to our formās submit handler. The logic will be as follows:
- First, check for anĀ
AbortController
Ā for any previous requests. If one exists, abort it.
- Next, create anĀ
AbortController
Ā for the current request that can be aborted on subsequent requests.
- Finally, when a request resolves, remove its correspondingĀ
AbortController
.
There are several ways to do this, but Iāll use aĀ WeakMap
Ā to store relationships between each submittedĀ <form>
Ā DOM node and its respectiveĀ AbortController
. When a form is submitted, we can check and update theĀ WeakMap
Ā accordingly.
const pendingForms = new WeakMap();
function handleSubmit(event) {
const form = event.currentTarget;
const previousController = pendingForms.get(form);
if (previousController) {
previousController.abort();
}
const controller = new AbortController();
pendingForms.set(form, controller);
fetch(form.action, {
method: form.method,
body: new FormData(form),
signal: controller.signal,
}).then(() => {
pendingForms.delete(form);
});
event.preventDefault();
}
const forms = document.querySelectorAll('form');
for (const form of forms) {
form.addEventListener('submit', handleSubmit);
}
The key thing is being able to associate an abort controller with its corresponding form. Using the formās DOM node as theĀ WeakMap
ās key is a convenient way to do that.
With that in place, we can add theĀ AbortController
ās signal to theĀ fetch
Ā request, abort any previous controllers, add new ones, and delete them upon completion.
Hopefully, that all makes sense.
Now, if we smash that formās submit button a bunch of times, we can see that all of the API requests except the most recent one get canceled.
This means any function responding to that HTTP response will behave more as you would expect.
Now, if we use that same counting and logging logic we have above, we can smash the submit button seven times and would see six exceptions (due to theĀ AbortController
) and one log of ā7ā in the console.
If we submit again and allow enough time for the request to resolve, weād see ā8ā in the console. And if we smash the submit button a bunch of times, again, weāll continue to see the exceptions and final request count in the right order.
If you want to add some more logic to avoid seeing DOMExceptions in the console when a request is aborted, you can add aĀ .catch()
Ā block after yourĀ fetch
Ā request and check if the errorās name matches āAbortError
ā:
fetch(url, {
signal: controller.signal,
}).catch((error) => {
// If the request was aborted, do nothing
if (error.name === 'AbortError') return;
// Otherwise, handle the error here or throw it back to the console
throw error
});
Closing
This whole post was focused on JavaScript-enhanced forms, but itās probably a good idea to include anĀ AbortController
Ā any time you create aĀ fetch
Ā request. Itās really too bad itās not built into the API already. But hopefully, this shows you a good method for including it.
Itās also worth mentioning that this approach does not prevent the user from spamming the submit button a bunch of times. The button is still clickable, and the request still fires off, it just provides a more consistent way of dealing with responses.
Unfortunately, if a userĀ doesĀ spam a submit button, those requests would still go to your backend and could use consume a bunch of unnecessary resources.
Some naive solutions may be disabling the submit button, using aĀ
They donāt address abuse via scripted requests.
To address abuse from too many requests to your server, you would probably want to set up someĀ
Itās also worth mentioning that rate limiting doesnāt solve the original problem of duplicate requests, race conditions, and inconsistent UI updates. Ideally, we should use both to cover both ends.
Anyway, thatās all Iāve got for today. If you want to watch a video that covers this same subject, watch this.
https://www.youtube.com/watch?v=w8ZIoLnh1Dc&embedable=true
Thank you so much for reading. If you liked this article, pleaseĀ
Also published here.