@tanstack/react-store
Version:
Framework agnostic type-safe store w/ reactive framework adapters
1 lines • 1.75 kB
Source Map (JSON)
{"version":3,"file":"useStore.cjs","sources":["../../src/useStore.ts"],"sourcesContent":["import { useCallback } from 'react'\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'\nimport type { AnyAtom } from '@tanstack/store'\n\ntype SyncExternalStoreSubscribe = Parameters<\n typeof useSyncExternalStoreWithSelector\n>[0]\n\nfunction defaultCompare<T>(a: T, b: T) {\n return a === b\n}\n\nexport function useStore<TAtom extends AnyAtom | undefined, T>(\n atom: TAtom,\n selector: (\n snapshot: TAtom extends { get: () => infer TSnapshot }\n ? TSnapshot\n : undefined,\n ) => T,\n compare: (a: T, b: T) => boolean = defaultCompare,\n): T {\n const subscribe: SyncExternalStoreSubscribe = useCallback(\n (handleStoreChange) => {\n if (!atom) {\n return () => {}\n }\n const { unsubscribe } = atom.subscribe(handleStoreChange)\n return unsubscribe\n },\n [atom],\n )\n\n const boundGetSnapshot = useCallback(() => atom?.get(), [atom])\n\n const selectedSnapshot = useSyncExternalStoreWithSelector(\n subscribe,\n boundGetSnapshot,\n boundGetSnapshot,\n selector,\n compare,\n )\n\n return selectedSnapshot\n}\n"],"names":["useCallback","useSyncExternalStoreWithSelector"],"mappings":";;;;AAQA,SAAS,eAAkB,GAAM,GAAM;AACrC,SAAO,MAAM;AACf;AAEO,SAAS,SACd,MACA,UAKA,UAAmC,gBAChC;AACH,QAAM,YAAwCA,MAAAA;AAAAA,IAC5C,CAAC,sBAAsB;AACrB,UAAI,CAAC,MAAM;AACT,eAAO,MAAM;AAAA,QAAC;AAAA,MAChB;AACA,YAAM,EAAE,YAAA,IAAgB,KAAK,UAAU,iBAAiB;AACxD,aAAO;AAAA,IACT;AAAA,IACA,CAAC,IAAI;AAAA,EAAA;AAGP,QAAM,mBAAmBA,MAAAA,YAAY,MAAM,MAAM,OAAO,CAAC,IAAI,CAAC;AAE9D,QAAM,mBAAmBC,aAAAA;AAAAA,IACvB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EAAA;AAGF,SAAO;AACT;;"}