Photo by Jose Aragones on Unsplash
With this in mind, I researched the Fetch API to see if it supports timeout in its interface, request body, or header. Unfortunately, it does not have the timeout option that other promise-based HTTP clients support.
An example of Axios's timeout option
In this post, we will discuss how to use an AbortController to set a timeout when using Fetch API. We will be using React to develop our frontend application. (Note: You can use this same approach on other frontend libraries/frameworks.).
We completed this project in a Codesandbox, and you can fork it to run the code.
Before diving in, we need to understand what an AbortController is and how it works. AbortController is an object that lets us abort one or more web requests as and when desired. It contains a
signal property and an
abort method for communicating and stopping requests respectively as needed.
A fetch function without a timeout looks like this:
using the Fetch API without a timeout
To integrate AbortController with the fetch API, we need to create a
Timeout function as shown below:
using the abort contoller
The above code performs these tasks:
Timeoutfunction and an instance of the AbortController.
setTimeoutfunction to trigger the
abortmethod after a specified time(convert to seconds by multiplying by 1000) and returns the controller.
Finally, to use the
timeout function, we need to modify the fetch request object signal as shown below:
updated App.js with a timeout of 10 seconds
This post discussed how to use AbortController to set a timeout when making REST API call with the Fetch API.