@sv-use/core
Version:
A collection of Svelte 5 utilities.
32 lines (31 loc) • 1.27 kB
JavaScript
/**
* Copied and adapted from Svecosystem Runed, all credit goes to them.
* https://github.com/svecosystem/runed/blob/main/packages/runed/src/lib/utilities/watch/watch.svelte.ts
*/
import { untrack } from 'svelte';
import { normalizeValue } from '../__internal__/utils.svelte.js';
/**
* Triggers a callback when a dependency changes.
* @param deps The dependencies to watch.
* @param fn The callback to trigger when a dependency changes.
* @param options Additional options to customize the behavior.
* @note `watch` is a `$effect` but supplies the previous value(s) as the second argument.
* @see https://svelte-librarian.github.io/sv-use/docs/core/watch
*/
export function watch(deps, fn, options = {}) {
const { runOnMounted = true } = options;
let active = runOnMounted;
let previousValues = undefined;
$effect(() => {
const values = $state.snapshot(Array.isArray(deps) ? deps.map(normalizeValue) : deps());
if (!active) {
active = true;
previousValues = values;
return;
}
// @ts-expect-error Should fix type error on `previousValues`
const cleanup = untrack(() => fn(values, previousValues));
previousValues = values;
return cleanup;
});
}