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

react-use-abortable-effect

v1.1.0

Published

React hook to work with abortable side-effects in a safer way.

Downloads

4

Readme

useAbortableEffect

React hook to work with abortable effects in a safe way.

An effect started with useAbortableEffect can be aborted at any time and will be aborted when the React component is unmounted.

While some libraries like axios and Bluebird support aborting effects, and it wouldn't be too complicated to abort then when a component is unmounted, useAbortableEffect does this automatically, which I think is safer, and usign the standard AbortController. This means effects used with useAbortableEffect can be used anywhere: in a redux store, outside of the React lifecycle, etc, without any dependency.

More importantly, with just useEffect you'd likely need some way for your effect error handler to check the mount status of your component in order to prevent setting state or other unintended work when the abort occurs in the context of unmounting the component, which is a bad practice.

I considered accepting a callback to handle the abort scenario, instead of throwing an error, but keeping it like the standard makes the code more portable and durable, at the cost of ergonomics.

Example

This is a TypeScript example.

import React, { FunctionComponent, useState } from "react";

import useAbortableEffect from "./useAbortableEffect";

type DownloadStatus =
  | { status: "Initial" | "InProgress" | "Complete" }
  | { status: "Error"; errorMessage: string };

const assertNever = (unexpected: never): never => {
  throw new Error(`Unexpected value: ${unexpected}`);
};

const LargeVideoDownloader: FunctionComponent<{}> = () => {
  const downloadEffect = useAbortableEffect(signal =>
    fetch("some_url", { signal })
  );
  const [downloadStatus, setDownloadStatus] = useState<DownloadStatus>({
    status: "Initial"
  });

  const startDownloading = async () => {
    setDownloadStatus({ status: "InProgress" });
    try {
      await downloadEffect.start();
    } catch (e) {
      const errorMessage = e instanceof Error ? e.message : e.toString();
      // Here we would capture the abort as well as any other error.
      // You can tell the abort case if you need to by checking its name:
      // e.name === 'AbortError'
      setDownloadStatus({ status: "Error", errorMessage });
      return;
    }
    setDownloadStatus({ status: "Complete" });
  };

  switch (downloadStatus.status) {
    case "Initial":
      return (
        <p>
          Ready?<button onClick={startDownloading}>Go!</button>
        </p>
      );
    case "InProgress":
      return (
        <p>
          Downloading... <button onClick={downloadEffect.abort}>Cancel</button>
        </p>
      );
    case "Complete":
      return (
        <p>
          Download complete! :){" "}
          <button onClick={downloadEffect.abort}>Download again because yes</button>
        </p>
      );
    case "Error":
      return <p>Error while downloading: {downloadStatus.errorMessage}. <button onClick={startDownloading}>Retry</button></p>;
    default:
      return assertNever(downloadStatus);
  }
};

export default LargeVideoDownloader;