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 Learn React with TypeScript 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.