Skip to content

Commit

Permalink
feat(useAbortSignal): new hook to help cleanup event listeners and re…
Browse files Browse the repository at this point in the history
…quests
  • Loading branch information
cristinecula committed Oct 27, 2023
1 parent 30abd09 commit 82f9c30
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/hooks/use-abort-signal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useEffect, useMemo } from 'haunted';

export const useAbortSignal = () => {
const { controller, signal } = useMemo(() => {
const controller = new AbortController(),
signal = controller.signal;
return { controller, signal };
}, []);

useEffect(() => () => controller.abort(), []);

return signal;
};
34 changes: 34 additions & 0 deletions test/use-abort-signal.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useAbortSignal } from '../src/hooks/use-abort-signal';
import { component } from 'haunted';
import { assert, html, fixture } from '@open-wc/testing';
import { spy } from 'sinon';

customElements.define(
'use-abort-signal',
component((host) => {
host.current = useAbortSignal();
}),
);

suite('useAbortSignal', () => {
test('creates an abort signal', async () => {
const result = await fixture(html`<use-abort-signal></use-abort-signal>`);

assert.isOk(result.current);
assert.instanceOf(result.current, AbortSignal);
});

test('signal aborts when the component is destroyed', async () => {
const result = await fixture(html`<use-abort-signal></use-abort-signal>`);
const abortSignal = result.current;
const abortSpy = spy();

abortSignal.addEventListener('abort', abortSpy);

assert.isFalse(abortSignal.aborted);
assert.isFalse(abortSpy.called);
result.parentNode.removeChild(result);
assert.isTrue(abortSignal.aborted);
assert.isTrue(abortSpy.calledOnce);
});
});

0 comments on commit 82f9c30

Please sign in to comment.