deno.land / x / jotai@v1.8.4 / src / valtio / atomWithProxy.ts

atomWithProxy.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
66
67
68
69
70
71
import { snapshot, subscribe } from 'valtio/vanilla'import { atom } from 'jotai'import type { SetStateAction } from 'jotai'
const isObject = (x: unknown): x is object => typeof x === 'object' && x !== null
const applyChanges = <T extends object>(proxyObject: T, prev: T, next: T) => { ;(Object.getOwnPropertyNames(prev) as (keyof T)[]).forEach((key) => { if (!(key in next)) { delete proxyObject[key] } else if (Object.is(prev[key], next[key])) { // unchanged } else if ( isObject(proxyObject[key]) && isObject(prev[key]) && isObject(next[key]) ) { applyChanges( proxyObject[key] as unknown as object, prev[key] as unknown as object, next[key] as unknown as object ) } else { proxyObject[key] = next[key] } }) ;(Object.keys(next) as (keyof T)[]).forEach((key) => { if (!(key in prev)) { proxyObject[key] = next[key] } })}
type Options = { sync?: boolean}
// Currently atomWithProxy does not support overwriting Promise() with a primitive// due to the requirement of valtio types to always be symmetric.// Consequently, this would not work:// setStatusState({ ...state, status: 'newStatus' })// To overwrite a value that came from a promise you must do it via an immediately// resolving promise:// setStatusState({ ...state, status: Promise.resolve('newStatus') })export function atomWithProxy<Value extends object>( proxyObject: Value, options?: Options) { const baseAtom = atom(snapshot(proxyObject)) baseAtom.onMount = (setValue) => { const callback = () => { setValue(snapshot(proxyObject)) } const unsub = subscribe(proxyObject, callback, options?.sync) callback() return unsub } const derivedAtom = atom( (get) => get(baseAtom) as Value, (get, _set, update: SetStateAction<Value>) => { const newValue = typeof update === 'function' ? (update as (prev: Value) => Value)(get(baseAtom) as Value) : update applyChanges(proxyObject, snapshot(proxyObject) as Value, newValue) } ) return derivedAtom}
jotai

Version Info

Tagged at
2 years ago