@livestore/react 0.3.0-dev.9 → 0.3.1-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/LICENSE +201 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/LiveStoreContext.d.ts +10 -4
  4. package/dist/LiveStoreContext.d.ts.map +1 -1
  5. package/dist/LiveStoreContext.js +1 -11
  6. package/dist/LiveStoreContext.js.map +1 -1
  7. package/dist/LiveStoreProvider.d.ts +29 -12
  8. package/dist/LiveStoreProvider.d.ts.map +1 -1
  9. package/dist/LiveStoreProvider.js +84 -55
  10. package/dist/LiveStoreProvider.js.map +1 -1
  11. package/dist/LiveStoreProvider.test.js +80 -29
  12. package/dist/LiveStoreProvider.test.js.map +1 -1
  13. package/dist/__tests__/fixture.d.ts +122 -556
  14. package/dist/__tests__/fixture.d.ts.map +1 -1
  15. package/dist/__tests__/fixture.js +71 -30
  16. package/dist/__tests__/fixture.js.map +1 -1
  17. package/dist/experimental/components/LiveList.d.ts +2 -2
  18. package/dist/experimental/components/LiveList.d.ts.map +1 -1
  19. package/dist/experimental/components/LiveList.js +10 -6
  20. package/dist/experimental/components/LiveList.js.map +1 -1
  21. package/dist/mod.d.ts +4 -5
  22. package/dist/mod.d.ts.map +1 -1
  23. package/dist/mod.js +4 -5
  24. package/dist/mod.js.map +1 -1
  25. package/dist/useClientDocument.d.ts +61 -0
  26. package/dist/useClientDocument.d.ts.map +1 -0
  27. package/dist/useClientDocument.js +79 -0
  28. package/dist/useClientDocument.js.map +1 -0
  29. package/dist/useClientDocument.test.d.ts +2 -0
  30. package/dist/useClientDocument.test.d.ts.map +1 -0
  31. package/dist/useClientDocument.test.js +175 -0
  32. package/dist/useClientDocument.test.js.map +1 -0
  33. package/dist/useQuery.d.ts +25 -3
  34. package/dist/useQuery.d.ts.map +1 -1
  35. package/dist/useQuery.js +67 -47
  36. package/dist/useQuery.js.map +1 -1
  37. package/dist/useQuery.test.d.ts +1 -1
  38. package/dist/useQuery.test.d.ts.map +1 -1
  39. package/dist/useQuery.test.js +86 -24
  40. package/dist/useQuery.test.js.map +1 -1
  41. package/dist/useRcResource.d.ts +76 -0
  42. package/dist/useRcResource.d.ts.map +1 -0
  43. package/dist/useRcResource.js +152 -0
  44. package/dist/useRcResource.js.map +1 -0
  45. package/dist/useRcResource.test.d.ts +2 -0
  46. package/dist/useRcResource.test.d.ts.map +1 -0
  47. package/dist/useRcResource.test.js +122 -0
  48. package/dist/useRcResource.test.js.map +1 -0
  49. package/dist/useStore.d.ts +9 -0
  50. package/dist/useStore.d.ts.map +1 -0
  51. package/dist/useStore.js +28 -0
  52. package/dist/useStore.js.map +1 -0
  53. package/dist/utils/useStateRefWithReactiveInput.d.ts.map +1 -1
  54. package/package.json +20 -13
  55. package/src/LiveStoreContext.ts +11 -16
  56. package/src/LiveStoreProvider.test.tsx +176 -37
  57. package/src/LiveStoreProvider.tsx +156 -81
  58. package/src/__snapshots__/useClientDocument.test.tsx.snap +613 -0
  59. package/src/__snapshots__/useQuery.test.tsx.snap +2011 -0
  60. package/src/__tests__/fixture.tsx +74 -47
  61. package/src/experimental/components/LiveList.tsx +10 -7
  62. package/src/mod.ts +5 -6
  63. package/src/useClientDocument.test.tsx +306 -0
  64. package/src/useClientDocument.ts +157 -0
  65. package/src/useQuery.test.tsx +182 -71
  66. package/src/useQuery.ts +95 -58
  67. package/src/useRcResource.test.tsx +167 -0
  68. package/src/useRcResource.ts +182 -0
  69. package/src/useStore.ts +36 -0
  70. package/dist/useAtom.d.ts +0 -5
  71. package/dist/useAtom.d.ts.map +0 -1
  72. package/dist/useAtom.js +0 -38
  73. package/dist/useAtom.js.map +0 -1
  74. package/dist/useRow.d.ts +0 -50
  75. package/dist/useRow.d.ts.map +0 -1
  76. package/dist/useRow.js +0 -93
  77. package/dist/useRow.js.map +0 -1
  78. package/dist/useRow.test.d.ts +0 -2
  79. package/dist/useRow.test.d.ts.map +0 -1
  80. package/dist/useRow.test.js +0 -202
  81. package/dist/useRow.test.js.map +0 -1
  82. package/dist/useScopedQuery.d.ts +0 -33
  83. package/dist/useScopedQuery.d.ts.map +0 -1
  84. package/dist/useScopedQuery.js +0 -87
  85. package/dist/useScopedQuery.js.map +0 -1
  86. package/dist/useScopedQuery.test.d.ts +0 -2
  87. package/dist/useScopedQuery.test.d.ts.map +0 -1
  88. package/dist/useScopedQuery.test.js +0 -60
  89. package/dist/useScopedQuery.test.js.map +0 -1
  90. package/src/__snapshots__/useRow.test.tsx.snap +0 -360
  91. package/src/useAtom.ts +0 -52
  92. package/src/useRow.test.tsx +0 -344
  93. package/src/useRow.ts +0 -188
  94. package/src/useScopedQuery.test.tsx +0 -96
  95. package/src/useScopedQuery.ts +0 -143
  96. package/tsconfig.json +0 -20
  97. package/vitest.config.js +0 -17
@@ -0,0 +1,152 @@
1
+ import * as React from 'react';
2
+ /**
3
+ * Creates a reference-counted resource object that is "stable" across React lifecycles.
4
+ *
5
+ * The hook is primarily intended for creating stateful objects or entities where:
6
+ * 1) reference identity is crucial (e.g. stateful objects, references, ...)
7
+ * and needed to persist across multiple component instances
8
+ * 2) the `create`/`dispose` functions might be effectful and can be called exactly once per key
9
+ *
10
+ * **Goals:**
11
+ * - Guarantee stable reference identity for stateful entities that are created via the `create` function.
12
+ * - Strong guarantees about the `create`/`dispose` calls (i.e. exactly one `create`/`dispose` call per key)
13
+ * - Ensure that such state is retained across component re-mounts, even in development environments like
14
+ * React Strict Mode or during Fast Refresh.
15
+ * - Automatically handle resource disposal by decrementing a reference count and disposing of the resource
16
+ * when no components are using it.
17
+ *
18
+ * **Behavior:**
19
+ * - On the first render with a specific key, the `create` function is invoked to create the stateful entity,
20
+ * and the resource is stored in a cache with a reference count set to 1.
21
+ * - If another component renders with the same key, the cached entity is reused and its reference count is incremented.
22
+ * - When a component renders with a new key, the previous key's reference count is decremented and, if it reaches zero,
23
+ * the `dispose` function is called for that resource.
24
+ * - Upon component unmount, the reference count is decremented, leading to disposal (via the `dispose` function)
25
+ * if the reference count drops to zero. An unmount is either detected via React's `useEffect` callback or
26
+ * in the useMemo hook when the key changes.
27
+ *
28
+ * Why this is needed in LiveStore:
29
+ * Let's first take a look at the "trivial implementation":
30
+ *
31
+ * ```ts
32
+ * const useSimpleResource = <T>(create: () => T, dispose: (resource: T) => void) => {
33
+ * const val = React.useMemo(() => create(), [create])
34
+ *
35
+ * React.useEffect(() => {
36
+ * return () => {
37
+ * dispose(val)
38
+ * }
39
+ * }, [dispose, val])
40
+
41
+ * return val
42
+ * }
43
+ * ```
44
+ *
45
+ * LiveStore uses this hook to create LiveQuery instances which are stateful and must not be leaked.
46
+ * The simple implementation above would leak the LiveQuery instance if the component is unmounted or props change.
47
+ *
48
+ * **Usage:**
49
+ * ```tsx
50
+ * // Create a stateful object instance for a unique key and share it between components.
51
+ * const statefulObject = useRcResource(
52
+ * 'stable-object-key',
53
+ * () => createObjectInstance(),
54
+ * (object) => object.dispose()
55
+ * );
56
+ * ```
57
+ *
58
+ * **Caveats:**
59
+ * - The `create` function is intentionally omitted from the dependency array in `useMemo` to prevent
60
+ * unintended re-creations of the stateful entity. Avoid closing over changing values within `create`
61
+ * or include them in the `key`.
62
+ * - Ensure that the `dispose` function is stable or properly memoized as its reference is used in a `useEffect`.
63
+ * - Although the caching mechanism prevents duplicate instance creation for the same key, the strategy
64
+ * can interact in unexpected ways with React’s development patterns. Please report any issues if encountered.
65
+ *
66
+ * @template T The type of the stateful entity managed by the hook.
67
+ * @param key A unique identifier for the stateful entity. A change in this key triggers a disposal of the previous resource.
68
+ * @param create Function to create the stateful entity when it does not exist in the cache.
69
+ * @param dispose Function to dispose of the stateful entity when it’s no longer needed. Needs to be stable.
70
+ * @param _options Optional. Additional options such as a debug print callback for logging purposes.
71
+ * @returns The stateful entity corresponding to the provided key.
72
+ */
73
+ export const useRcResource = (key, create, dispose, _options) => {
74
+ const keyRef = React.useRef(undefined);
75
+ const didDisposeInMemo = React.useRef(false);
76
+ // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
77
+ const resource = React.useMemo(() => {
78
+ // console.debug('useMemo', key)
79
+ if (didDisposeInMemo.current) {
80
+ // console.debug('useMemo', key, 'skip')
81
+ const cachedItem = cache.get(key);
82
+ if (cachedItem !== undefined && cachedItem._tag === 'active') {
83
+ return cachedItem.resource;
84
+ }
85
+ }
86
+ // Check if the key has changed (or is undefined)
87
+ if (keyRef.current !== undefined && keyRef.current !== key) {
88
+ // If the key has changed, decrement the reference on the previous key
89
+ const previousKey = keyRef.current;
90
+ const cachedItemForPreviousKey = cache.get(previousKey);
91
+ if (cachedItemForPreviousKey !== undefined && cachedItemForPreviousKey._tag === 'active') {
92
+ // previousKeyRef.current = previousKey
93
+ cachedItemForPreviousKey.rc--;
94
+ // console.debug('useMemo', key, 'rc--', previousKey, cachedItemForPreviousKey.rc)
95
+ if (cachedItemForPreviousKey.rc === 0) {
96
+ // Clean up the stateful resource if no longer referenced
97
+ dispose(cachedItemForPreviousKey.resource);
98
+ cache.set(previousKey, { _tag: 'destroyed' });
99
+ didDisposeInMemo.current = true;
100
+ }
101
+ }
102
+ }
103
+ const cachedItem = cache.get(key);
104
+ if (cachedItem !== undefined && cachedItem._tag === 'active') {
105
+ // In React Strict Mode, the `useMemo` hook is called multiple times,
106
+ // so we only increment the reference from the first call for this component.
107
+ cachedItem.rc++;
108
+ // console.debug('rc++', cachedItem.rc, ...(_options?.debugPrint?.(cachedItem.resource) ?? []))
109
+ return cachedItem.resource;
110
+ }
111
+ // Create a new stateful resource if not cached
112
+ const resource = create();
113
+ cache.set(key, { _tag: 'active', rc: 1, resource });
114
+ return resource;
115
+ // Dependency is deliberately limited to `key` to avoid unintended re-creations.
116
+ // eslint-disable-next-line react-hooks/exhaustive-deps
117
+ }, [key]);
118
+ // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
119
+ React.useEffect(() => {
120
+ return () => {
121
+ if (didDisposeInMemo.current) {
122
+ // console.debug('unmount', keyRef.current, 'skip')
123
+ didDisposeInMemo.current = false;
124
+ return;
125
+ }
126
+ // console.debug('unmount', keyRef.current)
127
+ const cachedItem = cache.get(key);
128
+ // If the stateful resource is already cleaned up, do nothing.
129
+ if (cachedItem === undefined || cachedItem._tag === 'destroyed')
130
+ return;
131
+ cachedItem.rc--;
132
+ // console.debug('rc--', cachedItem.rc, ...(_options?.debugPrint?.(cachedItem.resource) ?? []))
133
+ if (cachedItem.rc === 0) {
134
+ dispose(cachedItem.resource);
135
+ cache.delete(key);
136
+ }
137
+ };
138
+ // We assume the `dispose` function is stable and won't change across renders
139
+ // eslint-disable-next-line react-hooks/exhaustive-deps
140
+ }, [key]);
141
+ keyRef.current = key;
142
+ return resource;
143
+ };
144
+ // NOTE Given `useMemo` will be called multiple times (e.g. when using React Strict mode or Fast Refresh),
145
+ // we are using this cache to avoid starting multiple queries/spans for the same component.
146
+ // This is somewhat against some recommended React best practices, but it should be fine in our case below.
147
+ // Please definitely open an issue if you see or run into any problems with this approach!
148
+ const cache = new Map();
149
+ export const __resetUseRcResourceCache = () => {
150
+ cache.clear();
151
+ };
152
+ //# sourceMappingURL=useRcResource.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRcResource.js","sourceRoot":"","sources":["../src/useRcResource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,GAAW,EACX,MAAe,EACf,OAAuC,EACvC,QAAwE,EACrE,EAAE;IACL,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAAqB,SAAS,CAAC,CAAA;IAC1D,MAAM,gBAAgB,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IAE5C,yEAAyE;IACzE,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,GAA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,GAAG,GAAG,EAAE;IAC5C,KAAK,CAAC,KAAK,EAAE,CAAA;AACf,CAAC,CAAA"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=useRcResource.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRcResource.test.d.ts","sourceRoot":"","sources":["../src/useRcResource.test.tsx"],"names":[],"mappings":""}
@@ -0,0 +1,122 @@
1
+ import * as ReactTesting from '@testing-library/react';
2
+ import * as React from 'react';
3
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
4
+ import { __resetUseRcResourceCache, useRcResource } from './useRcResource.js';
5
+ describe.each([{ strictMode: true }, { strictMode: false }])('useRcResource (strictMode=%s)', ({ strictMode }) => {
6
+ beforeEach(() => {
7
+ __resetUseRcResourceCache();
8
+ });
9
+ const wrapper = strictMode ? React.StrictMode : React.Fragment;
10
+ it('should create a stateful entity using make and call cleanup on unmount', () => {
11
+ const makeSpy = vi.fn(() => Symbol('statefulResource'));
12
+ const cleanupSpy = vi.fn();
13
+ const { result, unmount } = ReactTesting.renderHook(() => useRcResource('key-1', makeSpy, cleanupSpy), { wrapper });
14
+ expect(makeSpy).toHaveBeenCalledTimes(1);
15
+ expect(result.current).toBeDefined();
16
+ expect(cleanupSpy).toHaveBeenCalledTimes(0);
17
+ unmount();
18
+ expect(cleanupSpy).toHaveBeenCalledTimes(1);
19
+ });
20
+ it('should reuse the same entity when the key remains unchanged', () => {
21
+ const makeSpy = vi.fn(() => Symbol('statefulResource'));
22
+ const cleanupSpy = vi.fn();
23
+ const { result, rerender, unmount } = ReactTesting.renderHook(({ key }) => useRcResource(key, makeSpy, cleanupSpy), { initialProps: { key: 'consistent-key' }, wrapper });
24
+ const instance1 = result.current;
25
+ // Re-render with the same key
26
+ rerender({ key: 'consistent-key' });
27
+ const instance2 = result.current;
28
+ expect(instance1).toBe(instance2);
29
+ expect(makeSpy).toHaveBeenCalledTimes(1);
30
+ unmount();
31
+ expect(cleanupSpy).toHaveBeenCalledTimes(1);
32
+ });
33
+ it('should dispose the previous instance when the key changes', () => {
34
+ const makeSpy = vi.fn(() => Symbol('statefulResource'));
35
+ const cleanupSpy = vi.fn();
36
+ const { result, rerender, unmount } = ReactTesting.renderHook(({ key }) => useRcResource(key, makeSpy, cleanupSpy), { initialProps: { key: 'a' }, wrapper });
37
+ const instanceA = result.current;
38
+ // Change the key; this should trigger the disposal of the 'a' instance
39
+ rerender({ key: 'b' });
40
+ const instanceB = result.current;
41
+ expect(instanceA).not.toBe(instanceB);
42
+ expect(makeSpy).toHaveBeenCalledTimes(2);
43
+ expect(cleanupSpy).toHaveBeenCalledTimes(1);
44
+ unmount();
45
+ expect(cleanupSpy).toHaveBeenCalledTimes(2);
46
+ });
47
+ it('should not dispose the entity until all consumers unmount', () => {
48
+ const makeSpy = vi.fn(() => Symbol('statefulResource'));
49
+ const cleanupSpy = vi.fn();
50
+ // Simulate two consumers using the same key independently.
51
+ const { unmount: unmount1 } = ReactTesting.renderHook(() => useRcResource('shared-key', makeSpy, cleanupSpy), {
52
+ wrapper,
53
+ });
54
+ const { unmount: unmount2, result } = ReactTesting.renderHook(() => useRcResource('shared-key', makeSpy, cleanupSpy), {
55
+ wrapper,
56
+ });
57
+ expect(result.current).toBeDefined();
58
+ expect(makeSpy).toHaveBeenCalledTimes(1);
59
+ // Unmount first consumer; the entity should remain active.
60
+ unmount1();
61
+ expect(cleanupSpy).not.toHaveBeenCalled();
62
+ // Unmount second consumer; now the entity is disposed.
63
+ unmount2();
64
+ expect(cleanupSpy).toHaveBeenCalledTimes(1);
65
+ });
66
+ it('should handle rapid key changes correctly', () => {
67
+ const makeSpy = vi.fn(() => Symbol('statefulResource'));
68
+ const cleanupSpy = vi.fn();
69
+ const { rerender, unmount } = ReactTesting.renderHook(({ key }) => useRcResource(key, makeSpy, cleanupSpy), {
70
+ initialProps: { key: '1' },
71
+ wrapper,
72
+ });
73
+ // Rapid sequence of key changes.
74
+ rerender({ key: '2' });
75
+ rerender({ key: '3' });
76
+ // Expect three creations: one each for keys '1', '2', '3'
77
+ expect(makeSpy).toHaveBeenCalledTimes(3);
78
+ // Cleanup should have been triggered for key '1' and key '2'
79
+ expect(cleanupSpy).toHaveBeenCalledTimes(2);
80
+ unmount();
81
+ // Unmounting the final consumer disposes the key '3' instance.
82
+ expect(cleanupSpy).toHaveBeenCalledTimes(3);
83
+ });
84
+ });
85
+ // This code was useful to better understand the hook behaviour with and without strict mode
86
+ // describe('debug', () => {
87
+ // const useStrictTest = (key: string) => {
88
+ // const id = React.useId()
89
+ // console.log(key, 'id', id)
90
+ // const x = React.useMemo(() => {
91
+ // console.log('useMemo', key)
92
+ // return 'hi' + key
93
+ // }, [key])
94
+ // React.useEffect(() => {
95
+ // console.log('useEffect', key)
96
+ // return () => {
97
+ // console.log('unmount', key)
98
+ // }
99
+ // }, [])
100
+ // return x
101
+ // }
102
+ // it('strict mode component', () => {
103
+ // console.log('strict mode component')
104
+ // const Root = () => {
105
+ // useStrictTest('a')
106
+ // return null
107
+ // }
108
+ // const { unmount } = ReactTesting.render(
109
+ // <React.StrictMode>
110
+ // <Root />
111
+ // </React.StrictMode>,
112
+ // )
113
+ // unmount()
114
+ // })
115
+ // it('strict mode hook', () => {
116
+ // console.log('strict mode hook')
117
+ // const wrapper: React.FC<{ children: React.ReactNode }> = React.StrictMode
118
+ // const { unmount } = ReactTesting.renderHook(() => useStrictTest('b'), { wrapper })
119
+ // unmount()
120
+ // })
121
+ // })
122
+ //# sourceMappingURL=useRcResource.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useRcResource.test.js","sourceRoot":"","sources":["../src/useRcResource.test.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,YAAY,MAAM,wBAAwB,CAAA;AACtD,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAA;AAE7D,OAAO,EAA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+BAA+B;AAE/B,oCAAoC;AACpC,kCAAkC;AAClC,wBAAwB;AACxB,cAAc;AAEd,4BAA4B;AAC5B,oCAAoC;AACpC,qBAAqB;AACrB,oCAAoC;AACpC,QAAQ;AACR,WAAW;AAEX,aAAa;AACb,IAAI;AAEJ,wCAAwC;AACxC,2CAA2C;AAC3C,2BAA2B;AAC3B,2BAA2B;AAC3B,oBAAoB;AACpB,QAAQ;AACR,+CAA+C;AAC/C,2BAA2B;AAC3B,mBAAmB;AACnB,6BAA6B;AAC7B,QAAQ;AAER,gBAAgB;AAChB,OAAO;AAEP,mCAAmC;AACnC,sCAAsC;AACtC,gFAAgF;AAChF,yFAAyF;AAEzF,gBAAgB;AAChB,OAAO;AACP,KAAK"}
@@ -0,0 +1,9 @@
1
+ import type { Store } from '@livestore/livestore';
2
+ import type { ReactApi } from './LiveStoreContext.js';
3
+ export declare const withReactApi: (store: Store) => Store & ReactApi;
4
+ export declare const useStore: (options?: {
5
+ store?: Store;
6
+ }) => {
7
+ store: Store & ReactApi;
8
+ };
9
+ //# sourceMappingURL=useStore.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useStore.d.ts","sourceRoot":"","sources":["../src/useStore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAA;AAGjD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAA;AAKrD,eAAO,MAAM,YAAY,GAAI,OAAO,KAAK,KAAG,KAAK,GAAG,QAQnD,CAAA;AAED,eAAO,MAAM,QAAQ,GAAI,UAAU;IAAE,KAAK,CAAC,EAAE,KAAK,CAAA;CAAE,KAAG;IAAE,KAAK,EAAE,KAAK,GAAG,QAAQ,CAAA;CAiB/E,CAAA"}
@@ -0,0 +1,28 @@
1
+ import React from 'react';
2
+ import { LiveStoreContext } from './LiveStoreContext.js';
3
+ import { useClientDocument } from './useClientDocument.js';
4
+ import { useQuery } from './useQuery.js';
5
+ export const withReactApi = (store) => {
6
+ // @ts-expect-error TODO properly implement this
7
+ // eslint-disable-next-line react-hooks/rules-of-hooks
8
+ store.useQuery = (queryDef) => useQuery(queryDef, { store });
9
+ // @ts-expect-error TODO properly implement this
10
+ // eslint-disable-next-line react-hooks/rules-of-hooks
11
+ store.useClientDocument = (table, idOrOptions, options) => useClientDocument(table, idOrOptions, options, { store });
12
+ return store;
13
+ };
14
+ export const useStore = (options) => {
15
+ if (options?.store !== undefined) {
16
+ return { store: withReactApi(options.store) };
17
+ }
18
+ // eslint-disable-next-line react-hooks/rules-of-hooks
19
+ const storeContext = React.useContext(LiveStoreContext);
20
+ if (storeContext === undefined) {
21
+ throw new Error(`useStore can only be used inside StoreContext.Provider`);
22
+ }
23
+ if (storeContext.stage !== 'running') {
24
+ throw new Error(`useStore can only be used after the store is running`);
25
+ }
26
+ return { store: withReactApi(storeContext.store) };
27
+ };
28
+ //# sourceMappingURL=useStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useStore.js","sourceRoot":"","sources":["../src/useStore.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAA;AAGzB,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAA;AACxD,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,KAAY,EAAoB,EAAE;IAC7D,gDAAgD;IAChD,sDAAsD;IACtD,KAAK,CAAC,QAAQ,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,QAAQ,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;IAC5D,gDAAgD;IAChD,sDAAsD;IACtD,KAAK,CAAC,iBAAiB,GAAG,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,EAAE,CAAC,iBAAiB,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,CAAC,CAAA;IACpH,OAAO,KAAyB,CAAA;AAClC,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,OAA2B,EAA+B,EAAE;IACnF,IAAI,OAAO,EAAE,KAAK,KAAK,SAAS,EAAE,CAAC;QACjC,OAAO,EAAE,KAAK,EAAE,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAA;IAC/C,CAAC;IAED,sDAAsD;IACtD,MAAM,YAAY,GAAG,KAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAA;IAEvD,IAAI,YAAY,KAAK,SAAS,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAA;IAC3E,CAAC;IAED,IAAI,YAAY,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;QACrC,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAA;IACzE,CAAC;IAED,OAAO,EAAE,KAAK,EAAE,YAAY,CAAC,YAAY,CAAC,KAAK,CAAC,EAAE,CAAA;AACpD,CAAC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"useStateRefWithReactiveInput.d.ts","sourceRoot":"","sources":["../../src/utils/useStateRefWithReactiveInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB;;;;;;;;;GASG;AACH,eAAO,MAAM,4BAA4B,GAAI,CAAC,cAChC,CAAC,KACZ,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI,CAwB/D,CAAA"}
1
+ {"version":3,"file":"useStateRefWithReactiveInput.d.ts","sourceRoot":"","sources":["../../src/utils/useStateRefWithReactiveInput.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB;;;;;;;;;GASG;AACH,eAAO,MAAM,4BAA4B,GAAI,CAAC,EAC5C,YAAY,CAAC,KACZ,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI,CAwB/D,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livestore/react",
3
- "version": "0.3.0-dev.9",
3
+ "version": "0.3.1-dev.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "exports": {
@@ -23,25 +23,32 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@opentelemetry/api": "1.9.0",
26
- "@livestore/db-schema": "0.3.0-dev.9",
27
- "@livestore/livestore": "0.3.0-dev.9",
28
- "@livestore/utils": "0.3.0-dev.9",
29
- "@livestore/common": "0.3.0-dev.9"
26
+ "@livestore/common": "0.3.1-dev.0",
27
+ "@livestore/utils": "0.3.1-dev.0",
28
+ "@livestore/livestore": "0.3.1-dev.0"
30
29
  },
31
30
  "devDependencies": {
32
- "@opentelemetry/sdk-trace-base": "^1.30.1",
33
- "@testing-library/react": "^16.0.1",
34
- "@types/react": "^19.0.8",
35
- "@types/react-dom": "^19.0.3",
31
+ "@opentelemetry/sdk-trace-base": "^2.0.0",
32
+ "@testing-library/dom": "^10.4.0",
33
+ "@testing-library/react": "^16.2.0",
34
+ "@types/react": "^19.1.2",
35
+ "@types/react-dom": "^19.0.4",
36
36
  "jsdom": "^26.0.0",
37
37
  "react": "^19.0.0",
38
38
  "react-dom": "^19.0.0",
39
39
  "react-window": "^1.8.11",
40
- "typescript": "^5.7.2",
41
- "vite": "^6.0.11",
42
- "vitest": "^2.1.4",
43
- "@livestore/web": "0.3.0-dev.9"
40
+ "typescript": "^5.8.3",
41
+ "vite": "^6.3.4",
42
+ "vitest": "^3.1.2",
43
+ "@livestore/utils-dev": "0.3.1-dev.0",
44
+ "@livestore/adapter-web": "0.3.1-dev.0"
44
45
  },
46
+ "files": [
47
+ "package.json",
48
+ "src",
49
+ "dist"
50
+ ],
51
+ "license": "Apache-2.0",
45
52
  "peerDependencies": {
46
53
  "react": "~19.0.0"
47
54
  },
@@ -1,19 +1,14 @@
1
- import type { Store } from '@livestore/livestore'
2
- import type { LiveStoreContextRunning as LiveStoreContext_ } from '@livestore/livestore/effect'
3
- import React, { useContext } from 'react'
1
+ import type { LiveStoreContextRunning } from '@livestore/livestore'
2
+ import React from 'react'
4
3
 
5
- export const LiveStoreContext = React.createContext<LiveStoreContext_ | undefined>(undefined)
4
+ import type { useClientDocument } from './useClientDocument.js'
5
+ import type { useQuery } from './useQuery.js'
6
6
 
7
- export const useStore = (): { store: Store } => {
8
- const storeContext = useContext(LiveStoreContext)
9
-
10
- if (storeContext === undefined) {
11
- throw new Error(`useStore can only be used inside StoreContext.Provider`)
12
- }
13
-
14
- if (storeContext.stage !== 'running') {
15
- throw new Error(`useStore can only be used after the store is running`)
16
- }
17
-
18
- return storeContext
7
+ export type ReactApi = {
8
+ useQuery: typeof useQuery
9
+ useClientDocument: typeof useClientDocument
19
10
  }
11
+
12
+ export const LiveStoreContext = React.createContext<
13
+ { stage: 'running'; store: LiveStoreContextRunning['store'] & ReactApi } | undefined
14
+ >(undefined)