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:
- First, we are going to import the CancelTokenSource type from axios:
import axios, { CancelTokenSource } from "axios";
- Let's add a cancel token and a loading flag to our state:
interface IState { posts: IPost[]; error: string; cancelTokenSource?: CancelTokenSource; loading: boolean;}
- 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.
- Next, we'll generate the cancel token source and add it to the state, just before we make the ...