deno.land / x / jotai@v1.8.4 / src / devtools / useAtomsDebugValue.ts

useAtomsDebugValue.ts
نووسراو ببینە
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { useContext, useDebugValue, useEffect, useState } from 'react'import { SECRET_INTERNAL_getScopeContext as getScopeContext } from 'jotai'import type { Atom } from '../core/atom'import { DEV_GET_ATOM_STATE, DEV_GET_MOUNTED, DEV_GET_MOUNTED_ATOMS, DEV_SUBSCRIBE_STATE,} from '../core/store'import type { AtomState, Store } from '../core/store'
type Scope = NonNullable<Parameters<typeof getScopeContext>[0]>
const atomToPrintable = (atom: Atom<unknown>) => atom.debugLabel || atom.toString()
const stateToPrintable = ([store, atoms]: [Store, Atom<unknown>[]]) => Object.fromEntries( atoms.flatMap((atom) => { const mounted = store[DEV_GET_MOUNTED]?.(atom) if (!mounted) { return [] } const dependents = mounted.t const atomState = store[DEV_GET_ATOM_STATE]?.(atom) || ({} as AtomState) return [ [ atomToPrintable(atom), { ...('e' in atomState && { error: atomState.e }), ...('p' in atomState && { promise: atomState.p }), ...('v' in atomState && { value: atomState.v }), dependents: Array.from(dependents).map(atomToPrintable), }, ], ] }) )
type Options = { scope?: Scope enabled?: boolean}
// We keep a reference to the atoms,// so atoms aren't garbage collected by the WeakMap of mounted atomsexport const useAtomsDebugValue = (options?: Options) => { const enabled = options?.enabled ?? __DEV__ const ScopeContext = getScopeContext(options?.scope) const { s: store } = useContext(ScopeContext) const [atoms, setAtoms] = useState<Atom<unknown>[]>([]) useEffect(() => { if (!enabled) { return } const callback = () => { setAtoms(Array.from(store[DEV_GET_MOUNTED_ATOMS]?.() || [])) } const unsubscribe = store[DEV_SUBSCRIBE_STATE]?.(callback) callback() return unsubscribe }, [enabled, store]) useDebugValue([store, atoms], stateToPrintable)}
jotai

Version Info

Tagged at
2 years ago