import { useSnapshot } from '../use-snapshot.js' import { isFunction } from '../../utils/index.js' import type { VanillaStore } from '../../vanilla/create.js' import type { SnapshotOptions } from '../use-snapshot.js' import type { StoreUseSnapshot } from '../create-with-hooks.js' import type { SnapshotSelector } from '../../vanilla/snapshot.js' export interface WithUseSnapshotContributes { /** * Get the snapshot of the state. */ useSnapshot: StoreUseSnapshot } /** * Enhances a store with `useSnapshot` method that returns a snapshot of the store's state. * * @param store - The store to enhance. * @returns The enhanced store. * * @since 0.2.0 * * @example * * ```tsx * const store = withUseSnapshot( * createVanilla({ * count: 123, * info: { name: 'Viki' }, * }), * ) * * // in normal JS/TS * console.log(store.snapshot(), store.snapshot((s) => s.count)) * * // in React component * export function App() { * const { count } = store.useSnapshot() * const count = store.useSnapshot((s) => s.count) * } * * ``` */ export function withUseSnapshot>( store: Store ): Store & WithUseSnapshotContributes { const boundUseSnapshot: StoreUseSnapshot = ( selectorOrOption?: | SnapshotOptions | SnapshotSelector | undefined, maybeOptions?: SnapshotOptions ) => { let options: SnapshotOptions | undefined let selector: SnapshotSelector | undefined if (selectorOrOption && !isFunction(selectorOrOption)) { options = selectorOrOption selector = undefined } else { options = maybeOptions selector = selectorOrOption } return useSnapshot(store.mutate, selector, options) } return { ...store, useSnapshot: boundUseSnapshot, } }