deno.land / x / jotai@v1.8.4 / src / utils / useHydrateAtoms.ts

useHydrateAtoms.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
import { useContext } from 'react'import { SECRET_INTERNAL_getScopeContext as getScopeContext } from 'jotai'import type { Atom } from '../core/atom'import type { ScopeContainer } from '../core/contexts'import { RESTORE_ATOMS } from '../core/store'
type Scope = NonNullable<Parameters<typeof getScopeContext>[0]>
const hydratedMap: WeakMap< ScopeContainer, WeakSet<Atom<unknown>>> = new WeakMap()
export function useHydrateAtoms( values: Iterable<readonly [Atom<unknown>, unknown]>, scope?: Scope) { const ScopeContext = getScopeContext(scope) const scopeContainer = useContext(ScopeContext) const store = scopeContainer.s
const hydratedSet = getHydratedSet(scopeContainer) const tuplesToRestore = [] for (const tuple of values) { const atom = tuple[0] if (!hydratedSet.has(atom)) { hydratedSet.add(atom) tuplesToRestore.push(tuple) } } if (tuplesToRestore.length) { store[RESTORE_ATOMS](tuplesToRestore) }}
function getHydratedSet(scopeContainer: ScopeContainer) { let hydratedSet = hydratedMap.get(scopeContainer) if (!hydratedSet) { hydratedSet = new WeakSet() hydratedMap.set(scopeContainer, hydratedSet) } return hydratedSet}
jotai

Version Info

Tagged at
2 years ago