Canceling requests

Allowing the user to cancel a request can improve the user experience in our app. We'll do this with the help of axios in this section:

  1. First, we are going to import the CancelTokenSource type from axios:
import axios, { CancelTokenSource } from "axios";
  1. Let's add a cancel token and a loading flag to our state:
interface IState {
posts: IPost[];
error: string;
cancelTokenSource?: CancelTokenSource;
loading: boolean;
}
  1. Let's initialize the loading state in the constructor: 
this.state = {
posts: [],
error: "",
loading: true
};

We've defined the cancel token as optional so we don't need to initialize it in the constructor.

  1. Next, we'll generate the cancel token source and add it to the state, just before we make the GET request:
public componentDidMount() {
const cancelToken = axios.CancelToken;
const cancelTokenSource = cancelToken.source();
this.setState({ cancelTokenSource });
axios
.get<IPost[]>(...)
.then(...)
.catch(...);
}
  1. We can then use the token in the GET request as follows:
.get<IPost[]>("https://jsonplaceholder.typicode.com/posts", {
cancelToken: cancelTokenSource.token,
...
})
  1. We can handle cancellations in the catch method as follows. Let's also set the loading state to false:
.catch(ex => {
const error = axios.isCancel(ex)
? "Request cancelled"
: ex.code === "ECONNABORTED"
? "A timeout has occurred"
: ex.response.status === 404
? "Resource not found"
: "An unexpected error has occurred";
this.setState({ error, loading: false });
});

So, we use the isCancel function in axios to check if the request has been canceled.

  1. While we are in the componentDidMount method, let's set the loading state to false in the then method as well:
.then(response => {
this.setState({ posts: response.data, loading: false });
})
  1. In the render method, let's add a Cancel button, which will allow the user to cancel the request:
{this.state.loading && (
<button onClick={this.handleCancelClick}>Cancel</button>
)}
<ul className="posts">...</ul>
  1. Let's implement the Cancel button handler that we have just referenced:
private handleCancelClick = () => {
if (this.state.cancelTokenSource) {
this.state.cancelTokenSource.cancel("User cancelled operation");
}
};

In order to cancel the request, the cancel method is called on the cancel token source.

So, users can now cancel requests by clicking the Cancel button.

  1. Now, this is going to be hard to test because the REST API we are using is really fast! So, in order to see a canceled request, let's cancel it in the componentDidMount method immediately after the request is sent:
axios
.get<IPost[]>( ... )
.then(response => { ... })
.catch(ex => { ... });

cancelTokenSource.cancel("User cancelled operation");

If we look at the running app, we should see verification that the request was cancelled by Request cancelled being displayed in red.

So, axios makes it really easy to improve our app's user experience by adding the ability to cancel requests.

Before we move on to the next section, wherein we look at using axios to create data, let's remove the line we just added to cancel the request immediately after it was made.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.190