Git Product home page Git Product logo

use-unmount-signal's Introduction

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

The HTML5 specification says:

Any web platform API using promises to represent operations that can be aborted must adhere to the following:

  • Accept AbortSignal objects through a signal dictionary member.
  • Convey that the operation got aborted by rejecting the promise with an "AbortError" DOMException.
  • Reject immediately if the AbortSignal's aborted flag is already set, otherwise:
  • Use the abort algorithms mechanism to observe changes to the AbortSignal object and do so in a manner that does not lead to clashes with other observers.

Calling any async function creates a promise. Therefore, authors of async functions need to follow the above guidance to write abortable functions.

import { useState } from 'react';
import useUnmountSignal from 'use-unmount-signal';

function Example() {
  const unmountSignal = useUnmountSignal();
  const [status, setStatus] = useState('ready');

  const handleClick = useCallback(
    async () => {
      if (unmountSignal.aborted) { throw new AbortError(); }

      const response = await fetch('https://ping.example.com', { signal: unmountSignal });
      if (unmountSignal.aborted) { throw new AbortError(); }

      // We are guaranteed that the component is still mounted at this point
      if (response.ok) {
        setStatus('OK');
      } else {
        setStatus(response.status);
      }
    },
    [unmountSignal, setStatus]
  );

  return <button onClick={handleClick}>Ping {status}</button>;
}

use-unmount-signal's People

Contributors

ide avatar fezvrasta avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.