Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update the integration and add support signals #9

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 39 additions & 19 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import type { ReadonlySignal } from '@preact/signals'
import type { Store, StoreValue } from 'nanostores'

type StoreKeys<T> = T extends { setKey: (k: infer K, v: any) => unknown }
export type StoreKeys<T> = T extends {
setKey: (k: infer K, v: never) => unknown
}
? K
: never

export interface UseStoreOptions<SomeStore> {
export interface UseStoreOptions<SomeStore, Value> {
/**
* Will re-render components only on specific key changes.
*/
keys?: StoreKeys<SomeStore>[]
/**
* Allows you to extract value from complex/deep objects
*/
selector?: (state: StoreValue<SomeStore>) => Value
}

/**
Expand All @@ -23,7 +30,7 @@ export interface UseStoreOptions<SomeStore> {
*
* export const Layout = () => {
* let page = useStore(router)
* if (page.router === 'home') {
* if (page.value.router === 'home') {
* return <HomePage />
* } else {
* return <Error404 />
Expand All @@ -32,29 +39,42 @@ export interface UseStoreOptions<SomeStore> {
* ```
*
* @param store Store instance.
* @param options
* @returns Store value.
*/
export function useStore<SomeStore extends Store>(
export function useStore<
ndt080 marked this conversation as resolved.
Show resolved Hide resolved
SomeStore extends Store,
Value = StoreValue<SomeStore>
>(
store: SomeStore,
options?: UseStoreOptions<SomeStore>
): StoreValue<SomeStore>
options: UseStoreOptions<SomeStore, Value> = {}
): ReadonlySignal<Value>

/**
* Batch React updates. It is just wrap for React’s `unstable_batchedUpdates`
* with fix for React Native.
* Subscribe to store changes and get store’s value.
*
* Can be user with store builder too.
*
* ```js
* import { batch } from 'nanostores/preact'
*
* React.useEffect(() => {
* let unbind = store.listen(() => {
* batch(() => {
* forceRender({})
* })
* })
* })
* import { useLegacyStore } from 'nanostores/preact'
*
* import { router } from '../store/router'
*
* export const Layout = () => {
* let page = useLegacyStore(router)
* if (page.router === 'home') {
* return <HomePage />
* } else {
* return <Error404 />
* }
* }
* ```
*
* @param cb Callback to run in batching.
* @param store Store instance.
* @param options
* @returns Store value.
*/
export function batch(cb: () => void): void
export function useLegacyStore<
SomeStore extends Store,
Value = StoreValue<SomeStore>
>(store: SomeStore, options: UseStoreOptions<SomeStore, Value> = {}): Value
64 changes: 34 additions & 30 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,39 @@
import { useComputed, useSignal } from '@preact/signals'
import { listenKeys } from 'nanostores'
import { useEffect, useState } from 'preact/hooks'
import { useSyncExternalStore } from 'preact/compat'
import { useCallback, useEffect } from 'preact/hooks'

export function useStore(store, opts = {}) {
let [, forceRender] = useState({})
let [valueBeforeEffect] = useState(store.get())
function defineStore(store, options = {}, syncExternalStoreFn) {
let subscribe = useCallback(
onChange => {
return options.keys
? listenKeys(store, options.keys, onChange)
: store.listen(onChange)
},
[options.keys, store]
)

let get = useCallback(() => {
return (options.selector ?? (s => s))(store.get())
}, [options.selector, store])

return syncExternalStoreFn(subscribe, get)
}

function useSignalLikeSyncExternalStore(subscribe, getSnapshot) {
let cache = useSignal(getSnapshot())

useEffect(() => {
valueBeforeEffect !== store.get() && forceRender({})
}, [])

useEffect(() => {
let batching, timer, unlisten
let rerender = () => {
if (!batching) {
batching = 1
timer = setTimeout(() => {
batching = undefined
forceRender({})
})
}
}
if (opts.keys) {
unlisten = listenKeys(store, opts.keys, rerender)
} else {
unlisten = store.listen(rerender)
}
return () => {
unlisten()
clearTimeout(timer)
}
}, [store, '' + opts.keys])

return store.get()
return subscribe(() => (cache.value = getSnapshot()))
}, [cache, subscribe, getSnapshot])

return useComputed(() => cache.value)
}

export function useStore(store, options = {}) {
return defineStore(store, options, useSignalLikeSyncExternalStore)
}

export function useLegacyStore(store, options = {}) {
return defineStore(store, options, useSyncExternalStore)
}
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
],
"peerDependencies": {
"nanostores": "^0.9.0 || ^0.10.0 || ^0.11.0",
"preact": ">=10.0.0"
"preact": ">=10.0.0",
"@preact/signals": ">=1.0.0"
},
"devDependencies": {
"@babel/core": "^7.25.2",
Expand All @@ -56,6 +57,7 @@
"nanodelay": "^2.0.2",
"nanostores": "^0.11.0",
"preact": "^10.23.1",
"@preact/signals": "^1.2.3",
"size-limit": "^11.1.4",
"tsx": "^4.16.5",
"typescript": "^5.5.4"
Expand Down Expand Up @@ -85,10 +87,10 @@
"size-limit": [
{
"import": {
"index.js": "{ useStore }",
"index.js": "{ useStore, useLegacyStore }",
"nanostores": "{ map, computed }"
},
"limit": "921 B"
"limit": "999 B"
}
]
}
Loading
Loading