This post will cover how to programmatically cancel a fetch request in a React and TypeScript app.

A React component

We have a typical React component that fetches some data from a web API and renders it:

export function App() {
  const [status, setStatus] = React.useState<"loading" | "loaded" | "cancelled">("loading");
  const [data, setData] = React.useState<Character | undefined>(undefined);

  React.useEffect(() => {
    getCharacter(1).then((character) => {
      setData(character);
      setStatus("loaded");
    });
  }, []);

  if (status === "loading") {
    return (
      <div>
        <div>loading ...</div>
        <button>Cancel</button>
      </div>
    );
  }
  if (status === "cancelled") {
    return <div>Cancelled</div>;
  }

  return <div>{data && <h3>{data.name}</h3>}</div>;
}

The data is fetched inside the getCharacter function inside a useEffect and put in state called data.

A state variable called status tracks where we are in the fetching process. Notice that a Cancel button is being rendered when the data is being fetched.

Cancel button

When the Cancel button is clicked, we want to cancel the fetch request.

#react #typescript #javascript #web-development

How to Cancel Fetch Request in React and TypeScript App
1.75 GEEK