Request Cancelation and Abortable Function
Learn about request cancellation with the example of autocomplete functionality and learn how the abortable function can be used to implement this functionality.
We'll cover the following...
Request cancelation
There are scenarios in which it’s a good idea to cancel a request. A good example is the autocomplete functionality.
Scenario
If we have a massive database, search queries can take a moment before a response is sent back from the server. Imagine a user is trying to search for a meal, and an API call is made any time a user types something into the search input. When a response is received, a list of meals is immediately displayed. A user types a few characters, and two API requests are made to search for a meal. The first request is sent with the query, “la”, whilst the second was with “lasagne.” However, suppose the first API request has finished after the second one. In such a scenario, the search results won’t display data for the latest search, but the old one instead. That’s not a great user experience. We can solve this problem by ensuring that the first request is canceled if the second request is made.
How to cancel the request
So far, we’ve been using the axios
library as an HTTP client. Requests can be canceled with axios
by creating a cancel
token that must be passed to an API request in the config
object. However, we don’t want to start creating cancel
tokens directly around the application because it would go against one of the API layers’ main principles. That is, an application doesn’t care about the internal ...