npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@closeio/use-abortable-effect

v1.0.0

Published

Super simple React hook for running abortable effects

Downloads

6,376

Readme

use-abortable-effect

NPM JavaScript Style Guide

Super simple React hook for running abortable effects based on the AbortController API.

Check the live DEMO.

Interested in working on projects like this? Close is looking for great engineers to join our team!

Install

yarn add @closeio/use-abortable-effect

Benefits

  • Extremely lightweight (less than 500B minzipped).
  • It uses the AbortController API and it is compatible with the fetch API.
  • If a browser does not support the AbortController API then the hook behaves exactly like a regular useEffect hook. See Can I Use for browser support overview.
  • No other 3rd-party dependencies.

API differences over useEffect

  • API is compatible with useEffect, where the effect function you pass-in accepts an AbortSignal instance as a param and you can return a cleanup function that accepts an AbortController instance.
  • Supports abortable fetch requests.
  • Supports running custom operations/computations that can be easily aborted.
  • Auto-aborts effects on re-run (or component unmount), unless you provide a custom cleanup function.
useEffect(() => {
  // do something

  return () => {
    /* cleanup */
  };
}, [deps]);

const abortControllerRef = useAbortableEffect(
  (abortSignal) => {
    // do something

    return (abortController) => {
      /* do cleanup, you should probably abort */
    };
  },
  [deps],
);

Usage

Abortable fetch requests

import React from 'react';
import useAbortableEffect from '@closeio/use-abortable-effect';

export default function MyAbortableFetchComponent() {
  const abortControllerRef = useAbortableEffect((abortSignal) =>
    fetch(url, { signal: abortSignal })
      .then(/* … */)
      .catch((rejection) => {
        if (rejection.name !== 'AbortError') {
          // Re-throw or handle non-abort rejection in another way.
          return Promise.reject(rejection);
        }
      }),
  );

  const handleManualAbort = () => abortControllerRef.current.abort();

  // …
}

Arbitrary computation that can be aborted

import React from 'react';
import useAbortableEffect from '@closeio/use-abortable-effect';

export default function MyAbortableComputationComponent() {
  const abortControllerRef = useAbortableEffect(abortSignal => {
    new Promise((resolve, reject) => {
      // Should be a DOMException per spec.
      const abortRejection = new DOMException(
        'Calculation aborted by the user',
        'AbortError',
      );

      // Handle when abort was requested before starting the computation.
      if (abortSignal.aborted) {
        return reject(abortRejection);
      }

      // This simulates an expensive computation.
      const timeout = setTimeout(() => resolve(1), 5000);

      // Listen for abort request.
      abortSignal.addEventListener('abort', () => {
        clearTimeout(timeout);
        reject(abortRejection);
      });
    })
      .then(/* … */)
      .catch(rejection => {
        if (rejection.name !== 'AbortError') {
          // Re-throw or handle non-abort rejection in another way.
          return Promise.reject(rejection);
        }
      }),
  });

  const handleManualAbort = () => abortControllerRef.current.abort();

  // …
}

Custom cleanup function

import React from 'react';
import useAbortableEffect from '@closeio/use-abortable-effect';

export default function MyCustomCleanupComponent() {
  const [gotAborted, setGotAborted] = useState(false);

  const abortControllerRef = useAbortableEffect((abortSignal) => {
    fetch(url, { signal: abortSignal })
      .then(/* … */)
      .catch((rejection) => {
        if (rejection.name !== 'AbortError') {
          // Re-throw or handle non-abort rejection in another way.
          return Promise.reject(rejection);
        }
      });

    // Just return a function like in `useEffect`, with the difference that you
    // get the abort controller (not a ref) as a param.
    return (controller) => {
      controller.abort();
      setGotAborted(true);
    };
  });

  const handleManualAbort = () => abortControllerRef.current.abort();

  // …
}

License

MIT © Close