solid-primitives icon indicating copy to clipboard operation
solid-primitives copied to clipboard

Feature request / suggestion: makeCleanupSignal

Open knpwrs opened this issue 10 months ago • 3 comments

Describe The Problem To Be Solved

Various web platform features accept the signal from an AbortController to cancel or remove effects. It would be great to tie this into the Solid component lifecycle automatically.

Suggest A Solution

I just implemented the following in my own project:

import { onCleanup } from 'solid-js';

export function makeCleanupSignal(condition = true) {
  const controller = new AbortController();

  onCleanup(() => {
    if (condition) {
      controller.abort();
    }
  });

  return controller.signal;
}

It's very simple, but allows for straightforward usage with web platform features (either ones that don't have primitives available, or when lower-level control is desired):

import { onMount } from 'solid-js';
import { makeCleanupSignal } from './util';

const signal = makeCleanupSignal();

onMount(() => {
  document.addEventListener('click', () => alert('Hey!'), { signal });
  fetch('//google.com', { signal }).then(/* */);
});

I would be happy to submit a pull request for this feature if such a feature would be desired. I'm open to other names as well so that makeCleanupSignal doesn't get confused with Solid signals.

knpwrs avatar Mar 30 '24 02:03 knpwrs