Timing out requests after a certain amount of time can improve the user experience in our app:
- Let's add a timeout to our request:
.get<IPost[]>("https://jsonplaceholder.typicode.com/posts", {
headers: {
"Content-Type": "application/json"
},
timeout: 1
})
So, adding a timeout to an axios request is super simple. We just add a timeout property to the options object with an appropriate number of milliseconds. We have specified just 1 millisecond, so that we can hopefully see the request timing out.
- Let's handle a timeout now in the catch method:
.catch(ex => {
const error =
ex.code === "ECONNABORTED"
? "A timeout has occurred"
: ex.response.status === 404
? "Resource not found"
: "An unexpected error has occurred";
this.setState({ error });
});
So, we check the code property in the caught error object in order to determine whether a timeout has occurred.
If we look at the running app, we should get confirmation that a timeout has occurred with A timeout has occurred displayed in red.
- Let's now change the timeout to something more sensible so that we can move on to looking at how we can allow users to cancel requests in the next section:
.get<IPost[]>("https://jsonplaceholder.typicode.com/posts", {
...
timeout: 5000
})