Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

utils.svelte.ts

57 lines1.7 KB

1import { untrack } from 'svelte'
2// modified from the great https://github.com/svecosystem/runed
3/**
4 * Runs an effect after (`'post'`) or before (`'pre'`) the DOM updates.
5 * @param flush - When to run the effect: `'post'` uses `$effect`, `'pre'` uses `$effect.pre`.
6 * @param effect - The effect to run. It may return a cleanup function.
7 */
8function runEffect(
9 flush: 'post' | 'pre',
10 effect: () => void | VoidFunction,
11): void {
12 switch (flush) {
13 case 'post':
14 $effect(effect)
15 break
16 case 'pre':
17 $effect.pre(effect)
18 break
19 }
21type Getter<T> = () => T
22/**
23 * Runs `effect` whenever the reactive state read by `sources` changes, even if they return the
24 * same values, skipping the first run. The effect receives the new and previous values, and is
25 * called untracked, so only `sources` are tracked.
26 * @param sources - The getter, or array of getters, to watch.
27 * @param flush - Whether to run after (`'post'`) or before (`'pre'`) the DOM updates.
28 * @param effect - Called with the new and previous values. It may return a cleanup function.
29 */
30export const watchChanges = <T>(
31 sources: Getter<T> | Array<Getter<T>>,
32 flush: 'post' | 'pre',
33 effect: (
34 values: T | Array<T>,
35 previousValues: T | undefined | Array<T | undefined>,
36 ) => void,
37) => {
38 let active = false
39 let previousValues: T | undefined | Array<T | undefined> = Array.isArray(
40 sources,
41 )
42 ? []
43 : undefined
44 runEffect(flush, () => {
45 const values = Array.isArray(sources)
46 ? sources.map((source) => source())
47 : sources()
48 if (!active) {
49 active = true
50 previousValues = values
51 return
52 }
53 const cleanup = untrack(() => effect(values, previousValues))
54 previousValues = values
55 return cleanup
56 })