Cancel Promises When A Component Is Unmounted – use-unmount-signal

use-unmount-signal 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.

How to use it:

1. Import the use-unmount-signal hook.

import useUnmountSignal from ‘use-unmount-signal’;

2. Basic usage.

function Example() {
  const unmountSignal = useUnmountSignal();
  return (
    <button
      onClick={() =>
        fetch('https://ping.example.com', { signal: unmountSignal })
      }>
      Ping
    </button>
  );
}

3. 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>;
}

Download Details:

Author: expo

Live Demo: View The Demo

Download Link: Download The Source Code

Official Website: https://github.com/expo/use-unmount-signal

License: MIT

You Might Be Interested In:

Add Comment