Neverending Plethora of Modules

    use-unmount-signal
    TypeScript icon, indicating that this package has built-in type declarations

    1.0.0 • Public • Published

    use-unmount-signal Tests codecov

    useUnmountSignal is a React Hook to cancel promises when a component is unmounted. It uses the W3C-standard AbortSignal API to notify compatible promises when the calling component is unmounted.

    API

    useUnmountSignal(): AbortSignal

    A React Hook that returns an AbortSignal object that is marked as aborted when the calling component is unmounted.

    Example

    import useUnmountSignal from 'use-unmount-signal';
    
    function Example() {
      // useUnmountSignal returns an AbortSignal object that APIs like fetch accept
      const unmountSignal = useUnmountSignal();
      return (
        <button
          onClick={() =>
            fetch('https://ping.example.com', { signal: unmountSignal })
          }>
          Ping
        </button>
      );
    }

    With async function event handlers

    import { useState } from 'react';
    import useUnmountSignal from 'use-unmount-signal';
    
    function Example() {
      const unmountSignal = useUnmountSignal();
      const [status, setStatus] = useState('ready');
    
      async function handleClick({ signal }) {
        if (signal.aborted) { throw new AbortError(); }
    
        const response = await fetch('https://ping.example.com', { signal });
        if (signal.aborted) { throw new AbortError(); }
    
        // We are guaranteed that the component is still mounted at this point
        if (response.ok) {
          setState('OK');
        } else {
          setState(response.status);
        }
      }
    
      return <button onClick={handleClick}>Ping {status}</button>;
    }

    Install

    npm i use-unmount-signal

    DownloadsWeekly Downloads

    365

    Version

    1.0.0

    License

    MIT

    Unpacked Size

    10.1 kB

    Total Files

    13

    Last publish

    Collaborators

    • kgc00
    • fiber-god
    • ide
    • brentvatne
    • ccheever
    • evanbacon
    • quinlanj
    • esamelson
    • expoadmin
    • charliecruzan
    • tsapeta
    • dsokal
    • tcdavis
    • exponent
    • wschurman
    • bbarthec
    • jkhales
    • wkozyra
    • bycedric
    • lukmccall
    • jonsamp
    • princefleaswallow
    • andyboythekid
    • kudochien