|
1 | 1 | /** @import { ComponentContext, ComponentContextLegacy } from '#client' */
|
2 | 2 | /** @import { EventDispatcher } from './index.js' */
|
3 | 3 | /** @import { NotFunction } from './internal/types.js' */
|
4 |
| -import { untrack } from './internal/client/runtime.js'; |
| 4 | +import { active_reaction, untrack } from './internal/client/runtime.js'; |
5 | 5 | import { is_array } from './internal/shared/utils.js';
|
6 | 6 | import { user_effect } from './internal/client/index.js';
|
7 | 7 | import * as e from './internal/client/errors.js';
|
@@ -44,6 +44,37 @@ if (DEV) {
|
44 | 44 | throw_rune_error('$bindable');
|
45 | 45 | }
|
46 | 46 |
|
| 47 | +/** |
| 48 | + * Returns an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that aborts when the current [derived](https://svelte.dev/docs/svelte/$derived) or [effect](https://svelte.dev/docs/svelte/$effect) re-runs or is destroyed. |
| 49 | + * |
| 50 | + * Must be called while a derived or effect is running. |
| 51 | + * |
| 52 | + * ```svelte |
| 53 | + * <script> |
| 54 | + * import { getAbortSignal } from 'svelte'; |
| 55 | + * |
| 56 | + * let { id } = $props(); |
| 57 | + * |
| 58 | + * async function getData(id) { |
| 59 | + * const response = await fetch(`/items/${id}`, { |
| 60 | + * signal: getAbortSignal() |
| 61 | + * }); |
| 62 | + * |
| 63 | + * return await response.json(); |
| 64 | + * } |
| 65 | + * |
| 66 | + * const data = $derived(await getData(id)); |
| 67 | + * </script> |
| 68 | + * ``` |
| 69 | + */ |
| 70 | +export function getAbortSignal() { |
| 71 | + if (active_reaction === null) { |
| 72 | + e.get_abort_signal_outside_reaction(); |
| 73 | + } |
| 74 | + |
| 75 | + return (active_reaction.ac ??= new AbortController()).signal; |
| 76 | +} |
| 77 | + |
47 | 78 | /**
|
48 | 79 | * `onMount`, like [`$effect`](https://svelte.dev/docs/svelte/$effect), schedules a function to run as soon as the component has been mounted to the DOM.
|
49 | 80 | * Unlike `$effect`, the provided function only runs once.
|
|
0 commit comments