Skip to content

Instantly share code, notes, and snippets.

@awreese
Last active October 5, 2022 23:35
Show Gist options
  • Save awreese/9ccffbd26eaf1115b9ab127482c12087 to your computer and use it in GitHub Desktop.
Save awreese/9ccffbd26eaf1115b9ab127482c12087 to your computer and use it in GitHub Desktop.
Cancellable Fetch React Hook
import { useEffect } from "react";
/**
* Cancellable Fetch request decorator - Higher Order Function
* --
* Decorates a standard fetch request with an AbortController's signal
* included with the fetch options.
*
* Based, in part, upon Oleg Lytvyn's ["How you can abort Fetch() request on a flight…" article](https://itnext.io/how-you-can-abort-fetch-request-on-a-flight-830a639b9b92)
*
* @returns {[(url: string, options: *) => Promise, () => void]} Returns an array of the decorated fetch request and abort functions.
*/
const cancellableFetch = () => {
const controller = new AbortController();
const { signal } = controller;
const wrappedFetch = (url, options) => fetch(url, { ...options, signal });
return [wrappedFetch, controller.abort.bind(controller)]; // bind the controller's `this` context to the abort function
};
/**
* useCancellableFetch
* --
* React hook to return a cancellable fetch function and abort functions.
* Fetch request automatically aborts upon rendering component unmounting
* or can be manually aborted at any time by calling `abort`
*/
const useCancellableFetch = () => {
const [wrappedFetch, abort] = cancellableFetch();
useEffect(() => {
console.log("Setting up effect on mount");
return () => {
console.warn("Tearing down on unmount, cancelling fetch request");
abort();
};
// eslint-disable-next-line
}, []);
return [wrappedFetch, abort];
};
export default useCancellableFetch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment