If you’ve ever found yourself knee-deep in a pile of asynchronous Fetch API calls, you’ll understand the desire to have a method for controlling them — something akin to a dog whistle, but for your code. Enter the Fetch API’s Signals. And no, they’re not Morse code, semaphore flags, or even smoke signals. They’re a mechanism to control our fetch
requests but with more grace and finesse than just shouting “STOP!” at your screen.
The Fetch API: A Quick Backstory
Fetch API, a JavaScript interface for making requests to the server in the browser, has become quite the darling of the web development scene. However, it had one glaring drawback for the longest time: it was like a rogue puppy. Once you let it off the leash, there was no calling it back.
Luckily for us, the clever folks who look after the Fetch API introduced a way to abort fetch requests. It’s called the AbortController, and its signal property is not nearly as violent as it sounds.
Fetch Signals: A New Leash of Life
Let’s dive into how to use signals in Fetch. First things first, we need to instantiate an AbortController
. In TypeScript, we can do it like this:
const controller = new AbortController();
When we create an AbortController
, it comes with an attached AbortSignal
(controller.signal). This signal can be passed to a fetch request like so:
fetch('https://api.example.com/data', { signal: controller.signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(err => { if (err.name === 'AbortError') { console.log('Fetch aborted'); } else { console.error('Another error', err); } });
Now, if we want to abort this request, we can call controller.abort()
. The fetch request will be immediately terminated, and the catch block will log “Fetch aborted”.
A Real-World Scenario: Fetch, Sit, Stay
Imagine you have a search feature on your site. As the user types, you fetch results from the server. If a new key is pressed before the fetch is complete, you want to cancel the old request before starting a new one. Here’s how we might handle that:
let controller = new AbortController(); document.querySelector('#search').addEventListener('keyup', (event) => { // Abort any previous fetches controller.abort(); // Create a new AbortController controller = new AbortController(); fetch(`https://api.example.com/search?q=${event.target.value}`, { signal: controller.signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(err => { if (err.name === 'AbortError') { console.log('Fetch aborted'); } else { console.error('Another error', err); } }); });
In this code, whenever a keyup event happens, we abort the previous fetch and start a new one. This keeps our fetches aligned with our user’s input and avoids duplicating redundant requests.
Conclusion
Fetch API’s Signals is a wonderful tool that can help you regain control over your fetch requests. They’re like a well-trained retriever, fetching exactly what you want and dropping it when you say “leave it”.
Remember, with great power comes great responsibility. Don’t become the crazy cat person of fetch requests. Instead, use signals to keep your requests in check.