[Medium] JavaScript Fetch causing unintended navigation (2020)
This post was originally published on Medium in 2020 and has been imported to my personal blog archive.
JavaScript Fetch causing unintended navigation
Hey, folks. Just here to share a quick code snippet with you that might save you 5 minutes.
The other day I was hitting a web service from a JavaScript function. For some reason, the service call was causing navigation and I couldn’t figure out why. I knew I was preventing the default event behavior, so that couldn’t be it. Here’s an example of what that code could have looked like:
// This was causing the navigation issue
function handleSubmit(event) {
event.preventDefault();
const data = await fetch('/api/endpoint', {
method: 'POST',
body: JSON.stringify(formData)
});
// Process response...
}
Some of you might have already caught the issue. I’ve turned my linting off here because it turns out that part of my problem was that my linting plugin had failed in VS Code. Here’s the code with the fix:
// The fix: add async to the function declaration
async function handleSubmit(event) {
event.preventDefault();
const data = await fetch('/api/endpoint', {
method: 'POST',
body: JSON.stringify(formData)
});
// Process response...
}
Without the async
declaration on my function, the await
was causing some funky behavior. I didn’t get any useful error messages in the console, even with preservation on.
Hope this helps someone.
P.S. Is your linter running? Better go catch it.