-
-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: cache snapshot & add option
deps
(#30)
* fix: cache snapshot & add option `deps` * Update size limit
- Loading branch information
Showing
3 changed files
with
24 additions
and
9 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,23 @@ | ||
import { listenKeys } from 'nanostores' | ||
import { useCallback, useSyncExternalStore } from 'react' | ||
import { useCallback, useRef, useSyncExternalStore } from 'react' | ||
|
||
export function useStore(store, { keys, deps = [store, keys] } = {}) { | ||
let snapshotRef = useRef() | ||
snapshotRef.current = store.get() | ||
|
||
export function useStore(store, opts = {}) { | ||
let subscribe = useCallback( | ||
onChange => | ||
opts.keys | ||
? listenKeys(store, opts.keys, onChange) | ||
: store.listen(onChange), | ||
[opts.keys, store] | ||
keys?.length > 0 | ||
? listenKeys(store, keys, emit(snapshotRef, onChange)) | ||
: store.listen(emit(snapshotRef, onChange)), | ||
deps | ||
) | ||
|
||
let get = store.get.bind(store) | ||
let get = () => snapshotRef.current | ||
|
||
return useSyncExternalStore(subscribe, get, get) | ||
} | ||
|
||
let emit = (snapshotRef, onChange) => value => { | ||
snapshotRef.current = value | ||
onChange() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -91,7 +91,7 @@ | |
"index.js": "{ useStore }", | ||
"nanostores": "{ map, computed }" | ||
}, | ||
"limit": "871 B" | ||
"limit": "901 B" | ||
} | ||
] | ||
} |