@livestore/react 0.4.0-dev.9 → 0.5.0-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.
- package/README.md +1 -1
- package/dist/.tsbuildinfo +1 -1
- package/dist/StoreRegistryContext.d.ts +56 -0
- package/dist/StoreRegistryContext.d.ts.map +1 -0
- package/dist/StoreRegistryContext.js +61 -0
- package/dist/StoreRegistryContext.js.map +1 -0
- package/dist/__tests__/fixture.d.ts +12 -283
- package/dist/__tests__/fixture.d.ts.map +1 -1
- package/dist/__tests__/fixture.js +12 -86
- package/dist/__tests__/fixture.js.map +1 -1
- package/dist/experimental/components/LiveList.d.ts +4 -2
- package/dist/experimental/components/LiveList.d.ts.map +1 -1
- package/dist/experimental/components/LiveList.js +11 -9
- package/dist/experimental/components/LiveList.js.map +1 -1
- package/dist/mod.d.ts +8 -5
- package/dist/mod.d.ts.map +1 -1
- package/dist/mod.js +6 -4
- package/dist/mod.js.map +1 -1
- package/dist/useClientDocument.d.ts +12 -4
- package/dist/useClientDocument.d.ts.map +1 -1
- package/dist/useClientDocument.js +4 -18
- package/dist/useClientDocument.js.map +1 -1
- package/dist/useClientDocument.test.js +28 -20
- package/dist/useClientDocument.test.js.map +1 -1
- package/dist/useQuery.d.ts +29 -8
- package/dist/useQuery.d.ts.map +1 -1
- package/dist/useQuery.js +43 -70
- package/dist/useQuery.js.map +1 -1
- package/dist/useQuery.test.js +67 -23
- package/dist/useQuery.test.js.map +1 -1
- package/dist/useRcResource.d.ts +1 -1
- package/dist/useRcResource.d.ts.map +1 -1
- package/dist/useRcResource.js +42 -35
- package/dist/useRcResource.js.map +1 -1
- package/dist/useRcResource.test.js +73 -50
- package/dist/useRcResource.test.js.map +1 -1
- package/dist/useStore.d.ts +74 -7
- package/dist/useStore.d.ts.map +1 -1
- package/dist/useStore.js +82 -16
- package/dist/useStore.js.map +1 -1
- package/dist/useStore.test.d.ts +2 -0
- package/dist/useStore.test.d.ts.map +1 -0
- package/dist/useStore.test.js +242 -0
- package/dist/useStore.test.js.map +1 -0
- package/dist/useSyncStatus.d.ts +22 -0
- package/dist/useSyncStatus.d.ts.map +1 -0
- package/dist/useSyncStatus.js +28 -0
- package/dist/useSyncStatus.js.map +1 -0
- package/package.json +60 -27
- package/src/StoreRegistryContext.tsx +70 -0
- package/src/__snapshots__/useClientDocument.test.tsx.snap +152 -78
- package/src/__snapshots__/useQuery.test.tsx.snap +12 -12
- package/src/__tests__/fixture.tsx +32 -135
- package/src/experimental/components/LiveList.tsx +25 -11
- package/src/mod.ts +8 -12
- package/src/useClientDocument.test.tsx +38 -23
- package/src/useClientDocument.ts +19 -38
- package/src/useQuery.test.tsx +110 -23
- package/src/useQuery.ts +74 -89
- package/src/useRcResource.test.tsx +116 -59
- package/src/useRcResource.ts +52 -38
- package/src/useStore.test.tsx +357 -0
- package/src/useStore.ts +115 -22
- package/src/useSyncStatus.ts +34 -0
- package/dist/LiveStoreContext.d.ts +0 -13
- package/dist/LiveStoreContext.d.ts.map +0 -1
- package/dist/LiveStoreContext.js +0 -3
- package/dist/LiveStoreContext.js.map +0 -1
- package/dist/LiveStoreProvider.d.ts +0 -65
- package/dist/LiveStoreProvider.d.ts.map +0 -1
- package/dist/LiveStoreProvider.js +0 -221
- package/dist/LiveStoreProvider.js.map +0 -1
- package/dist/LiveStoreProvider.test.d.ts +0 -2
- package/dist/LiveStoreProvider.test.d.ts.map +0 -1
- package/dist/LiveStoreProvider.test.js +0 -117
- package/dist/LiveStoreProvider.test.js.map +0 -1
- package/dist/utils/stack-info.d.ts +0 -4
- package/dist/utils/stack-info.d.ts.map +0 -1
- package/dist/utils/stack-info.js +0 -10
- package/dist/utils/stack-info.js.map +0 -1
- package/src/LiveStoreContext.ts +0 -14
- package/src/LiveStoreProvider.test.tsx +0 -248
- package/src/LiveStoreProvider.tsx +0 -413
- package/src/ambient.d.ts +0 -1
- package/src/utils/stack-info.ts +0 -13
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import {
|
|
2
|
+
act,
|
|
3
|
+
fireEvent,
|
|
4
|
+
type RenderHookResult,
|
|
5
|
+
type RenderResult,
|
|
6
|
+
render,
|
|
7
|
+
renderHook,
|
|
8
|
+
waitFor,
|
|
9
|
+
} from '@testing-library/react'
|
|
10
|
+
import * as React from 'react'
|
|
11
|
+
import { describe, expect, it, vi } from 'vitest'
|
|
12
|
+
|
|
13
|
+
import { makeInMemoryAdapter } from '@livestore/adapter-web'
|
|
14
|
+
import {
|
|
15
|
+
type RegistryStoreOptions,
|
|
16
|
+
type Store,
|
|
17
|
+
StoreInternalsSymbol,
|
|
18
|
+
StoreRegistry,
|
|
19
|
+
storeOptions,
|
|
20
|
+
} from '@livestore/livestore'
|
|
21
|
+
import { shouldNeverHappen } from '@livestore/utils'
|
|
22
|
+
|
|
23
|
+
import { schema } from './__tests__/fixture.tsx'
|
|
24
|
+
import { StoreRegistryProvider } from './StoreRegistryContext.tsx'
|
|
25
|
+
import { useStore } from './useStore.ts'
|
|
26
|
+
|
|
27
|
+
/** Verifies: LS.SYS.STORE-R06, LS.SYS.INT.REACT-R01 */
|
|
28
|
+
describe('experimental useStore', () => {
|
|
29
|
+
it('should return the same promise instance for concurrent getOrLoadStore calls', async () => {
|
|
30
|
+
const storeRegistry = new StoreRegistry()
|
|
31
|
+
const options = testStoreOptions()
|
|
32
|
+
|
|
33
|
+
// Make two concurrent calls during loading
|
|
34
|
+
const firstStore = storeRegistry.getOrLoadPromise(options)
|
|
35
|
+
const secondStore = storeRegistry.getOrLoadPromise(options)
|
|
36
|
+
|
|
37
|
+
// Both should be promises (store is loading)
|
|
38
|
+
expect(firstStore).toBeInstanceOf(Promise)
|
|
39
|
+
expect(secondStore).toBeInstanceOf(Promise)
|
|
40
|
+
|
|
41
|
+
// EXPECTED BEHAVIOR: Same promise instance for React.use() compatibility
|
|
42
|
+
// ACTUAL BEHAVIOR: Different promise instances (Effect.runPromise creates new wrapper)
|
|
43
|
+
expect(firstStore).toBe(secondStore)
|
|
44
|
+
|
|
45
|
+
// Cleanup
|
|
46
|
+
await firstStore
|
|
47
|
+
await cleanupAfterUnmount(() => {})
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('works with Suspense boundary', async () => {
|
|
51
|
+
const storeRegistry = new StoreRegistry()
|
|
52
|
+
const options = testStoreOptions()
|
|
53
|
+
|
|
54
|
+
let view: RenderResult | undefined
|
|
55
|
+
await act(async () => {
|
|
56
|
+
view = render(
|
|
57
|
+
<StoreRegistryProvider storeRegistry={storeRegistry}>
|
|
58
|
+
<React.Suspense fallback={makeSuspenseFallback()}>
|
|
59
|
+
<StoreConsumer options={options} />
|
|
60
|
+
</React.Suspense>
|
|
61
|
+
</StoreRegistryProvider>,
|
|
62
|
+
)
|
|
63
|
+
})
|
|
64
|
+
const renderedView = view ?? shouldNeverHappen('render failed')
|
|
65
|
+
|
|
66
|
+
// After loading completes, should show the actual content
|
|
67
|
+
await waitForSuspenseResolved(renderedView)
|
|
68
|
+
expect(renderedView.getByTestId('ready')).toBeDefined()
|
|
69
|
+
|
|
70
|
+
await cleanupAfterUnmount(() => renderedView.unmount())
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('does not re-suspend on subsequent renders when store is already loaded', async () => {
|
|
74
|
+
const storeRegistry = new StoreRegistry()
|
|
75
|
+
const options = testStoreOptions()
|
|
76
|
+
const Wrapper = ({ opts }: { opts: RegistryStoreOptions<typeof schema> }) => (
|
|
77
|
+
<StoreRegistryProvider storeRegistry={storeRegistry}>
|
|
78
|
+
<React.Suspense fallback={makeSuspenseFallback()}>
|
|
79
|
+
<StoreConsumer options={opts} />
|
|
80
|
+
</React.Suspense>
|
|
81
|
+
</StoreRegistryProvider>
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
let view: RenderResult | undefined
|
|
85
|
+
await act(async () => {
|
|
86
|
+
view = render(<Wrapper opts={options} />)
|
|
87
|
+
})
|
|
88
|
+
const renderedView = view ?? shouldNeverHappen('render failed')
|
|
89
|
+
|
|
90
|
+
// Wait for initial load
|
|
91
|
+
await waitForSuspenseResolved(renderedView)
|
|
92
|
+
expect(renderedView.getByTestId('ready')).toBeDefined()
|
|
93
|
+
|
|
94
|
+
// Rerender with new options object (but same storeId)
|
|
95
|
+
const rerenderOptions = cloneStoreOptions(options)
|
|
96
|
+
await act(async () => {
|
|
97
|
+
renderedView.rerender(<Wrapper opts={rerenderOptions} />)
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
// Should not show fallback
|
|
101
|
+
expect(renderedView.queryByTestId('fallback')).toBeNull()
|
|
102
|
+
expect(renderedView.getByTestId('ready')).toBeDefined()
|
|
103
|
+
|
|
104
|
+
await cleanupAfterUnmount(() => renderedView.unmount())
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it('throws when store loading fails', async () => {
|
|
108
|
+
const storeRegistry = new StoreRegistry()
|
|
109
|
+
const badOptions = testStoreOptions({
|
|
110
|
+
// @ts-expect-error - intentionally passing invalid adapter to trigger error
|
|
111
|
+
adapter: null,
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
// Pre-load the store to cache the error (error happens synchronously)
|
|
115
|
+
expect(() => storeRegistry.getOrLoadPromise(badOptions)).toThrow()
|
|
116
|
+
|
|
117
|
+
// Now when useStore tries to get it, it should throw synchronously
|
|
118
|
+
expect(() =>
|
|
119
|
+
renderHook(() => useStore(badOptions), {
|
|
120
|
+
wrapper: makeProvider(storeRegistry),
|
|
121
|
+
}),
|
|
122
|
+
).toThrow()
|
|
123
|
+
})
|
|
124
|
+
|
|
125
|
+
it.each([
|
|
126
|
+
{ label: 'non-strict mode', strictMode: false },
|
|
127
|
+
{ label: 'strict mode', strictMode: true },
|
|
128
|
+
])('works in $label', async ({ strictMode }) => {
|
|
129
|
+
const storeRegistry = new StoreRegistry()
|
|
130
|
+
const options = testStoreOptions()
|
|
131
|
+
|
|
132
|
+
let hook: RenderHookResult<Store<typeof schema>, RegistryStoreOptions<typeof schema>> | undefined
|
|
133
|
+
await act(async () => {
|
|
134
|
+
hook = renderHook(() => useStore(options), {
|
|
135
|
+
wrapper: makeProvider(storeRegistry, { suspense: true }),
|
|
136
|
+
reactStrictMode: strictMode,
|
|
137
|
+
})
|
|
138
|
+
})
|
|
139
|
+
const { result, unmount } = hook ?? shouldNeverHappen('renderHook failed')
|
|
140
|
+
|
|
141
|
+
// Wait for store to be ready
|
|
142
|
+
await waitForStoreReady(result)
|
|
143
|
+
expect(result.current[StoreInternalsSymbol].clientSession).toBeDefined()
|
|
144
|
+
|
|
145
|
+
await cleanupAfterUnmount(unmount)
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
it('handles switching between different storeId values', async () => {
|
|
149
|
+
const storeRegistry = new StoreRegistry()
|
|
150
|
+
|
|
151
|
+
const optionsA = testStoreOptions({ storeId: 'store-a' })
|
|
152
|
+
const optionsB = testStoreOptions({ storeId: 'store-b' })
|
|
153
|
+
|
|
154
|
+
let hook: RenderHookResult<Store<typeof schema>, RegistryStoreOptions<typeof schema>> | undefined
|
|
155
|
+
await act(async () => {
|
|
156
|
+
hook = renderHook((opts) => useStore(opts), {
|
|
157
|
+
initialProps: optionsA,
|
|
158
|
+
wrapper: makeProvider(storeRegistry, { suspense: true }),
|
|
159
|
+
})
|
|
160
|
+
})
|
|
161
|
+
const { result, rerender, unmount } = hook ?? shouldNeverHappen('renderHook failed')
|
|
162
|
+
|
|
163
|
+
// Wait for first store to load
|
|
164
|
+
await waitForStoreReady(result)
|
|
165
|
+
const storeA = result.current
|
|
166
|
+
expect(storeA[StoreInternalsSymbol].clientSession).toBeDefined()
|
|
167
|
+
|
|
168
|
+
// Switch to different storeId
|
|
169
|
+
await act(async () => {
|
|
170
|
+
rerender(optionsB)
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
// Wait for second store to load and verify it's different from the first
|
|
174
|
+
await waitFor(() => {
|
|
175
|
+
expect(result.current).not.toBe(storeA)
|
|
176
|
+
expect(result.current?.[StoreInternalsSymbol].clientSession).toBeDefined()
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
const storeB = result.current
|
|
180
|
+
expect(storeB[StoreInternalsSymbol].clientSession).toBeDefined()
|
|
181
|
+
expect(storeB).not.toBe(storeA)
|
|
182
|
+
|
|
183
|
+
await cleanupAfterUnmount(unmount)
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
it('does not block useActionState transitions from committing', async () => {
|
|
187
|
+
const storeRegistry = new StoreRegistry()
|
|
188
|
+
const options = testStoreOptions()
|
|
189
|
+
const getOrLoadSpy = vi.spyOn(storeRegistry, 'getOrLoadPromise')
|
|
190
|
+
|
|
191
|
+
let view: RenderResult | undefined
|
|
192
|
+
await act(async () => {
|
|
193
|
+
view = render(
|
|
194
|
+
<StoreRegistryProvider storeRegistry={storeRegistry}>
|
|
195
|
+
<React.Suspense fallback={makeSuspenseFallback()}>
|
|
196
|
+
<StoreWithActionState options={options} />
|
|
197
|
+
</React.Suspense>
|
|
198
|
+
</StoreRegistryProvider>,
|
|
199
|
+
)
|
|
200
|
+
})
|
|
201
|
+
const renderedView = view ?? shouldNeverHappen('render failed')
|
|
202
|
+
|
|
203
|
+
// Wait for store to load
|
|
204
|
+
await waitForSuspenseResolved(renderedView)
|
|
205
|
+
expect(renderedView.getByTestId('state').textContent).toBe('none')
|
|
206
|
+
expect(renderedView.getByTestId('pending').textContent).toBe('false')
|
|
207
|
+
|
|
208
|
+
// After store is loaded, clear spy to only track calls during the transition render
|
|
209
|
+
getOrLoadSpy.mockClear()
|
|
210
|
+
|
|
211
|
+
// Trigger a useActionState transition
|
|
212
|
+
await act(async () => {
|
|
213
|
+
fireEvent.click(renderedView.getByTestId('submit'))
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
// getOrLoadPromise must be called on each render (not cached via useMemo).
|
|
217
|
+
// When the initial Promise is cached, React.use() is called with a resolved Promise
|
|
218
|
+
// on every subsequent render, which blocks React transitions (e.g. useActionState)
|
|
219
|
+
// from ever committing in browser environments.
|
|
220
|
+
expect(getOrLoadSpy).toHaveBeenCalled()
|
|
221
|
+
|
|
222
|
+
// The transition should commit: state updates and isPending returns to false
|
|
223
|
+
await waitFor(() => {
|
|
224
|
+
expect(renderedView.getByTestId('state').textContent).toBe('updated')
|
|
225
|
+
expect(renderedView.getByTestId('pending').textContent).toBe('false')
|
|
226
|
+
})
|
|
227
|
+
|
|
228
|
+
getOrLoadSpy.mockRestore()
|
|
229
|
+
await cleanupAfterUnmount(() => renderedView.unmount())
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
// useStore doesn't handle unusedCacheTime=0 correctly because retain is called in useEffect (after render)
|
|
233
|
+
// See https://github.com/livestorejs/livestore/issues/916
|
|
234
|
+
it.skip('should load store with unusedCacheTime set to 0', async () => {
|
|
235
|
+
const storeRegistry = new StoreRegistry({ defaultOptions: { unusedCacheTime: 0 } })
|
|
236
|
+
const options = testStoreOptions({ unusedCacheTime: 0 })
|
|
237
|
+
const StoreConsumerWithVerification = ({ opts }: { opts: RegistryStoreOptions<typeof schema> }) => {
|
|
238
|
+
const store = useStore(opts)
|
|
239
|
+
// Verify store is usable - access internals to confirm it's not disposed
|
|
240
|
+
const clientSession = store[StoreInternalsSymbol].clientSession
|
|
241
|
+
return <div data-testid="ready" data-has-session={String(clientSession !== undefined)} />
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
let view: RenderResult | undefined
|
|
245
|
+
await act(async () => {
|
|
246
|
+
view = render(
|
|
247
|
+
<StoreRegistryProvider storeRegistry={storeRegistry}>
|
|
248
|
+
<React.Suspense fallback={makeSuspenseFallback()}>
|
|
249
|
+
<StoreConsumerWithVerification opts={options} />
|
|
250
|
+
</React.Suspense>
|
|
251
|
+
</StoreRegistryProvider>,
|
|
252
|
+
)
|
|
253
|
+
})
|
|
254
|
+
const renderedView = view ?? shouldNeverHappen('render failed')
|
|
255
|
+
|
|
256
|
+
await waitForSuspenseResolved(renderedView)
|
|
257
|
+
|
|
258
|
+
// Store should be usable while component is mounted
|
|
259
|
+
const readyElement = renderedView.getByTestId('ready')
|
|
260
|
+
expect(readyElement.getAttribute('data-has-session')).toBe('true')
|
|
261
|
+
|
|
262
|
+
// Allow some time to pass to ensure store isn't prematurely disposed
|
|
263
|
+
await new Promise((resolve) => setTimeout(resolve, 50))
|
|
264
|
+
|
|
265
|
+
// Store should still be usable after waiting
|
|
266
|
+
expect(readyElement.getAttribute('data-has-session')).toBe('true')
|
|
267
|
+
|
|
268
|
+
await cleanupAfterUnmount(() => renderedView.unmount())
|
|
269
|
+
})
|
|
270
|
+
})
|
|
271
|
+
|
|
272
|
+
const StoreConsumer = ({ options }: { options: RegistryStoreOptions<any> }) => {
|
|
273
|
+
useStore(options)
|
|
274
|
+
return <div data-testid="ready" />
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** Component that combines useStore with useActionState to test transition compatibility. */
|
|
278
|
+
const StoreWithActionState = ({ options }: { options: RegistryStoreOptions<any> }) => {
|
|
279
|
+
useStore(options)
|
|
280
|
+
|
|
281
|
+
const [state, dispatch, isPending] = React.useActionState(
|
|
282
|
+
(_prev: string | undefined, value: string): string => value,
|
|
283
|
+
undefined,
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
return (
|
|
287
|
+
<div>
|
|
288
|
+
<button
|
|
289
|
+
data-testid="submit"
|
|
290
|
+
// eslint-disable-next-line react-perf/jsx-no-new-function-as-prop -- test component
|
|
291
|
+
onClick={() => React.startTransition(() => dispatch('updated'))}
|
|
292
|
+
>
|
|
293
|
+
Submit
|
|
294
|
+
</button>
|
|
295
|
+
<div data-testid="state">{state ?? 'none'}</div>
|
|
296
|
+
<div data-testid="pending">{String(isPending)}</div>
|
|
297
|
+
</div>
|
|
298
|
+
)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const makeSuspenseFallback = () => React.createElement('div', { 'data-testid': 'fallback' })
|
|
302
|
+
|
|
303
|
+
const cloneStoreOptions = <TOptions extends object>(options: TOptions): TOptions => {
|
|
304
|
+
return { ...options }
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const makeProvider =
|
|
308
|
+
(storeRegistry: StoreRegistry, { suspense = false }: { suspense?: boolean } = {}) =>
|
|
309
|
+
({ children }: { children: React.ReactNode }) => {
|
|
310
|
+
let content = <StoreRegistryProvider storeRegistry={storeRegistry}>{children}</StoreRegistryProvider>
|
|
311
|
+
|
|
312
|
+
if (suspense !== undefined) {
|
|
313
|
+
content = <React.Suspense fallback={null}>{content}</React.Suspense>
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return content
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
let testStoreCounter = 0
|
|
320
|
+
|
|
321
|
+
const testStoreOptions = (overrides: Partial<RegistryStoreOptions<typeof schema>> = {}) =>
|
|
322
|
+
storeOptions({
|
|
323
|
+
storeId: overrides.storeId ?? `test-store-${testStoreCounter++}`,
|
|
324
|
+
schema,
|
|
325
|
+
adapter: makeInMemoryAdapter(),
|
|
326
|
+
...overrides,
|
|
327
|
+
})
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Cleans up after component unmount and waits for pending operations to settle.
|
|
331
|
+
*
|
|
332
|
+
* When components using stores unmount, the StoreRegistry schedules garbage collection
|
|
333
|
+
* timers for inactive stores. This helper waits for those timers to complete naturally.
|
|
334
|
+
*/
|
|
335
|
+
const cleanupAfterUnmount = async (cleanup: () => void): Promise<void> => {
|
|
336
|
+
cleanup()
|
|
337
|
+
// Allow any pending microtasks/timers to settle
|
|
338
|
+
await new Promise((resolve) => setTimeout(resolve, 100))
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Waits for React Suspense fallback to resolve and the actual content to render.
|
|
343
|
+
*/
|
|
344
|
+
const waitForSuspenseResolved = async (view: RenderResult): Promise<void> => {
|
|
345
|
+
await waitFor(() => expect(view.queryByTestId('fallback')).toBeNull())
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Waits for a store to be fully loaded and ready to use.
|
|
350
|
+
* The store is considered ready when it has a defined clientSession.
|
|
351
|
+
*/
|
|
352
|
+
const waitForStoreReady = async (result: { current: Store<any> }): Promise<void> => {
|
|
353
|
+
await waitFor(() => {
|
|
354
|
+
expect(result.current).not.toBeNull()
|
|
355
|
+
expect(result.current[StoreInternalsSymbol].clientSession).toBeDefined()
|
|
356
|
+
})
|
|
357
|
+
}
|
package/src/useStore.ts
CHANGED
|
@@ -1,36 +1,129 @@
|
|
|
1
|
-
import type { Store } from '@livestore/livestore'
|
|
2
1
|
import React from 'react'
|
|
3
2
|
|
|
4
|
-
import type {
|
|
5
|
-
import {
|
|
3
|
+
import type { LiveStoreSchema } from '@livestore/common/schema'
|
|
4
|
+
import type { RegistryStoreOptions, Store, SyncStatus } from '@livestore/livestore'
|
|
5
|
+
import type { Schema } from '@livestore/utils/effect'
|
|
6
|
+
|
|
7
|
+
import { useStoreRegistry } from './StoreRegistryContext.tsx'
|
|
6
8
|
import { useClientDocument } from './useClientDocument.ts'
|
|
7
9
|
import { useQuery } from './useQuery.ts'
|
|
10
|
+
import { useSyncStatus } from './useSyncStatus.ts'
|
|
8
11
|
|
|
9
|
-
|
|
10
|
-
|
|
12
|
+
/**
|
|
13
|
+
* Returns a store instance augmented with hooks (`store.useQuery()` and `store.useClientDocument()`) for reactive queries.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```tsx
|
|
17
|
+
* function Issue() {
|
|
18
|
+
* // Suspends until loaded or returns immediately if already loaded
|
|
19
|
+
* const issueStore = useStore(issueStoreOptions('abc123'))
|
|
20
|
+
* const [issue] = issueStore.useQuery(queryDb(tables.issue.select()))
|
|
21
|
+
*
|
|
22
|
+
* const toggleStatus = () =>
|
|
23
|
+
* issueStore.commit(
|
|
24
|
+
* issueEvents.issueStatusChanged({
|
|
25
|
+
* id: issue.id,
|
|
26
|
+
* status: issue.status === 'done' ? 'todo' : 'done',
|
|
27
|
+
* }),
|
|
28
|
+
* )
|
|
29
|
+
*
|
|
30
|
+
* const preloadParentIssue = (issueId: string) =>
|
|
31
|
+
* storeRegistry.preload({
|
|
32
|
+
* ...issueStoreOptions(issueId),
|
|
33
|
+
* unusedCacheTime: 10_000,
|
|
34
|
+
* })
|
|
35
|
+
*
|
|
36
|
+
* return (
|
|
37
|
+
* <>
|
|
38
|
+
* <h2>{issue.title}</h2>
|
|
39
|
+
* <button onClick={() => toggleStatus()}>Toggle Status</button>
|
|
40
|
+
* <button onMouseEnter={() => preloadParentIssue(issue.parentIssueId)}>Open Parent Issue</button>
|
|
41
|
+
* </>
|
|
42
|
+
* )
|
|
43
|
+
* }
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* @remarks
|
|
47
|
+
* - Suspends until the store is loaded.
|
|
48
|
+
* - Store is cached by its `storeId` in the `StoreRegistry`. Multiple calls with the same `storeId` return the same store instance.
|
|
49
|
+
* - Store is cached as long as it's being used, and after `unusedCacheTime` expires (default `60_000` ms in browser, `Infinity` in non-browser)
|
|
50
|
+
* - Default store options can be configured in `StoreRegistry` constructor.
|
|
51
|
+
* - Store options are only applied when the store is loaded. Subsequent calls with different options will not affect the store if it's already loaded and cached in the registry.
|
|
52
|
+
*
|
|
53
|
+
* @typeParam TSchema - The schema type for the store
|
|
54
|
+
* @returns The loaded store instance augmented with React hooks
|
|
55
|
+
* @throws unknown - store loading error or if called outside `<StoreRegistryProvider>`
|
|
56
|
+
*/
|
|
57
|
+
export const useStore = <
|
|
58
|
+
TSchema extends LiveStoreSchema,
|
|
59
|
+
TContext = {},
|
|
60
|
+
TSyncPayloadSchema extends Schema.Codec<Schema.Json, Schema.Json> = typeof Schema.Json,
|
|
61
|
+
>(
|
|
62
|
+
options: RegistryStoreOptions<TSchema, TContext, TSyncPayloadSchema>,
|
|
63
|
+
): Store<TSchema, TContext> & ReactApi => {
|
|
64
|
+
const storeRegistry = useStoreRegistry()
|
|
11
65
|
|
|
12
|
-
|
|
13
|
-
//
|
|
66
|
+
// Called on every render (intentionally not memoized). For already-loaded stores this returns
|
|
67
|
+
// the Store synchronously, so React.use() is skipped entirely. Caching the initial Promise via
|
|
68
|
+
// useMemo would cause React.use() to be called with a resolved Promise on subsequent renders,
|
|
69
|
+
// which blocks React transitions from committing.
|
|
70
|
+
const storeOrPromise = storeRegistry.getOrLoadPromise(options)
|
|
14
71
|
|
|
15
|
-
store
|
|
16
|
-
|
|
72
|
+
const store = storeOrPromise instanceof Promise ? React.use(storeOrPromise) : storeOrPromise
|
|
73
|
+
|
|
74
|
+
// NOTE: retain() must be declared AFTER the React.use() call above. When React.use() suspends
|
|
75
|
+
// the component, any hooks declared before it get committed while hooks after the suspension
|
|
76
|
+
// point (including those in the caller) don't. On re-render when the store resolves synchronously,
|
|
77
|
+
// those late hooks appear for the first time, causing a hook-order violation in strict mode.
|
|
78
|
+
// By placing useEffect after React.use(), no effect hooks are committed during suspension,
|
|
79
|
+
// so React treats all effects as fresh mounts on the first successful render.
|
|
80
|
+
//
|
|
81
|
+
// retain() is called in useEffect (after render), while getOrLoadPromise() is called during
|
|
82
|
+
// render. This creates a timing gap where with very short unusedCacheTime values (e.g., 0),
|
|
83
|
+
// the store could theoretically be disposed before the effect fires. In practice, this is not
|
|
84
|
+
// an issue with the default 60s cache time, but it becomes an issue when `unusedCacheTime` is
|
|
85
|
+
// configured to values less than ~100ms.
|
|
86
|
+
// See https://github.com/livestorejs/livestore/issues/916
|
|
87
|
+
React.useEffect(() => storeRegistry.retain(options), [storeRegistry, options])
|
|
88
|
+
|
|
89
|
+
return withReactApi(store)
|
|
17
90
|
}
|
|
18
91
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
92
|
+
/**
|
|
93
|
+
* React-specific methods added to the Store when used via React hooks.
|
|
94
|
+
*
|
|
95
|
+
* These methods are attached by `withReactApi()` and `useStore()`, allowing you
|
|
96
|
+
* to call `store.useQuery()` and `store.useClientDocument()` directly on the
|
|
97
|
+
* Store instance.
|
|
98
|
+
*/
|
|
99
|
+
export type ReactApi = {
|
|
100
|
+
/** Hook version of query subscription—re-renders component when query result changes */
|
|
101
|
+
useQuery: typeof useQuery
|
|
102
|
+
/** Hook for reading and writing client-document tables with React state semantics */
|
|
103
|
+
useClientDocument: typeof useClientDocument
|
|
104
|
+
/** Hook for subscribing to sync status changes */
|
|
105
|
+
useSyncStatus: () => SyncStatus
|
|
106
|
+
}
|
|
23
107
|
|
|
24
|
-
|
|
25
|
-
|
|
108
|
+
/**
|
|
109
|
+
* Augments a Store instance with React-specific methods (`useQuery`, `useClientDocument`).
|
|
110
|
+
*
|
|
111
|
+
* This is called automatically by `useStore()`. You typically don't need to call it
|
|
112
|
+
* directly unless you're building custom integrations.
|
|
113
|
+
*
|
|
114
|
+
* @internal
|
|
115
|
+
*/
|
|
116
|
+
export const withReactApi = <TSchema extends LiveStoreSchema, TContext = {}>(
|
|
117
|
+
store: Store<TSchema, TContext>,
|
|
118
|
+
): Store<TSchema, TContext> & ReactApi => {
|
|
119
|
+
// @ts-expect-error TODO properly implement this
|
|
120
|
+
store.useQuery = (queryable) => useQuery(queryable, { store })
|
|
26
121
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
}
|
|
122
|
+
// @ts-expect-error TODO properly implement this
|
|
123
|
+
store.useClientDocument = (table, idOrOptions, options) => useClientDocument(table, idOrOptions, options, { store })
|
|
30
124
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
125
|
+
// @ts-expect-error TODO properly implement this
|
|
126
|
+
store.useSyncStatus = () => useSyncStatus({ store })
|
|
34
127
|
|
|
35
|
-
return
|
|
128
|
+
return store as Store<TSchema, TContext> & ReactApi
|
|
36
129
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import React from 'react'
|
|
2
|
+
|
|
3
|
+
import type { Store, SyncStatus } from '@livestore/livestore'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* React hook that subscribes to sync status changes.
|
|
7
|
+
*
|
|
8
|
+
* Returns the current synchronization status between the client session and
|
|
9
|
+
* the leader thread. The component re-renders whenever the sync status changes.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```tsx
|
|
13
|
+
* function SyncIndicator() {
|
|
14
|
+
* const status = store.useSyncStatus()
|
|
15
|
+
* return <span>{status.isSynced ? '✓ Synced' : `Syncing (${status.pendingCount} pending)...`}</span>
|
|
16
|
+
* }
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* @param options - Options containing the store instance
|
|
20
|
+
* @returns The current sync status
|
|
21
|
+
*/
|
|
22
|
+
export const useSyncStatus = (options: { store: Store<any> }): SyncStatus => {
|
|
23
|
+
const { store } = options
|
|
24
|
+
|
|
25
|
+
const [status, setStatus] = React.useState<SyncStatus>(() => store.syncStatus())
|
|
26
|
+
|
|
27
|
+
React.useEffect(() => {
|
|
28
|
+
return store.subscribeSyncStatus(setStatus)
|
|
29
|
+
}, [store])
|
|
30
|
+
|
|
31
|
+
React.useDebugValue(`LiveStore:useSyncStatus:${status.isSynced === true ? 'synced' : 'pending'}`)
|
|
32
|
+
|
|
33
|
+
return status
|
|
34
|
+
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import type { LiveStoreContextRunning } from '@livestore/livestore';
|
|
2
|
-
import React from 'react';
|
|
3
|
-
import type { useClientDocument } from './useClientDocument.ts';
|
|
4
|
-
import type { useQuery } from './useQuery.ts';
|
|
5
|
-
export type ReactApi = {
|
|
6
|
-
useQuery: typeof useQuery;
|
|
7
|
-
useClientDocument: typeof useClientDocument;
|
|
8
|
-
};
|
|
9
|
-
export declare const LiveStoreContext: React.Context<{
|
|
10
|
-
stage: "running";
|
|
11
|
-
store: LiveStoreContextRunning["store"] & ReactApi;
|
|
12
|
-
} | undefined>;
|
|
13
|
-
//# sourceMappingURL=LiveStoreContext.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"LiveStoreContext.d.ts","sourceRoot":"","sources":["../src/LiveStoreContext.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAA;AACnE,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAA;AAC/D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAE7C,MAAM,MAAM,QAAQ,GAAG;IACrB,QAAQ,EAAE,OAAO,QAAQ,CAAA;IACzB,iBAAiB,EAAE,OAAO,iBAAiB,CAAA;CAC5C,CAAA;AAED,eAAO,MAAM,gBAAgB;WAClB,SAAS;WAAS,uBAAuB,CAAC,OAAO,CAAC,GAAG,QAAQ;cAC5D,CAAA"}
|
package/dist/LiveStoreContext.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"LiveStoreContext.js","sourceRoot":"","sources":["../src/LiveStoreContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAA;AAUzB,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC,aAAa,CAEjD,SAAS,CAAC,CAAA"}
|
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import type { Adapter, BootStatus, IntentionalShutdownCause, MigrationsReport, SyncError } from '@livestore/common';
|
|
2
|
-
import { UnexpectedError } from '@livestore/common';
|
|
3
|
-
import type { LiveStoreSchema } from '@livestore/common/schema';
|
|
4
|
-
import type { OtelOptions, Store } from '@livestore/livestore';
|
|
5
|
-
import { StoreInterrupted } from '@livestore/livestore';
|
|
6
|
-
import type { OtelTracer } from '@livestore/utils/effect';
|
|
7
|
-
import { Effect, Schema } from '@livestore/utils/effect';
|
|
8
|
-
import type * as otel from '@opentelemetry/api';
|
|
9
|
-
import React from 'react';
|
|
10
|
-
export interface LiveStoreProviderProps {
|
|
11
|
-
schema: LiveStoreSchema;
|
|
12
|
-
/**
|
|
13
|
-
* The `storeId` can be used to isolate multiple stores from each other.
|
|
14
|
-
* So it can be useful for multi-tenancy scenarios.
|
|
15
|
-
*
|
|
16
|
-
* The `storeId` is also used for persistence.
|
|
17
|
-
*
|
|
18
|
-
* Make sure to also configure `storeId` in LiveStore Devtools (e.g. in Vite plugin).
|
|
19
|
-
*
|
|
20
|
-
* @default 'default'
|
|
21
|
-
*/
|
|
22
|
-
storeId?: string;
|
|
23
|
-
boot?: (store: Store<LiveStoreSchema>, ctx: {
|
|
24
|
-
migrationsReport: MigrationsReport;
|
|
25
|
-
parentSpan: otel.Span;
|
|
26
|
-
}) => void | Promise<void> | Effect.Effect<void, unknown, OtelTracer.OtelTracer>;
|
|
27
|
-
otelOptions?: Partial<OtelOptions>;
|
|
28
|
-
renderLoading?: (status: BootStatus) => React.ReactNode;
|
|
29
|
-
renderError?: (error: UnexpectedError | unknown) => React.ReactNode;
|
|
30
|
-
renderShutdown?: (cause: IntentionalShutdownCause | StoreInterrupted | SyncError) => React.ReactNode;
|
|
31
|
-
adapter: Adapter;
|
|
32
|
-
/**
|
|
33
|
-
* In order for LiveStore to apply multiple events in a single render,
|
|
34
|
-
* you need to pass the `batchUpdates` function from either `react-dom` or `react-native`.
|
|
35
|
-
*
|
|
36
|
-
* ```ts
|
|
37
|
-
* // With React DOM
|
|
38
|
-
* import { unstable_batchedUpdates as batchUpdates } from 'react-dom'
|
|
39
|
-
*
|
|
40
|
-
* // With React Native
|
|
41
|
-
* import { unstable_batchedUpdates as batchUpdates } from 'react-native'
|
|
42
|
-
* ```
|
|
43
|
-
*/
|
|
44
|
-
batchUpdates: (run: () => void) => void;
|
|
45
|
-
disableDevtools?: boolean;
|
|
46
|
-
signal?: AbortSignal;
|
|
47
|
-
/**
|
|
48
|
-
* Currently only used in the web adapter:
|
|
49
|
-
* If true, registers a beforeunload event listener to confirm unsaved changes.
|
|
50
|
-
*
|
|
51
|
-
* @default true
|
|
52
|
-
*/
|
|
53
|
-
confirmUnsavedChanges?: boolean;
|
|
54
|
-
/**
|
|
55
|
-
* Payload that will be passed to the sync backend when connecting
|
|
56
|
-
*
|
|
57
|
-
* @default undefined
|
|
58
|
-
*/
|
|
59
|
-
syncPayload?: Schema.JsonValue;
|
|
60
|
-
debug?: {
|
|
61
|
-
instanceId?: string;
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
export declare const LiveStoreProvider: ({ renderLoading, renderError, renderShutdown, otelOptions, children, schema, storeId, boot, adapter, batchUpdates, disableDevtools, signal, confirmUnsavedChanges, syncPayload, debug, }: LiveStoreProviderProps & React.PropsWithChildren) => React.ReactNode;
|
|
65
|
-
//# sourceMappingURL=LiveStoreProvider.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"LiveStoreProvider.d.ts","sourceRoot":"","sources":["../src/LiveStoreProvider.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AACnH,OAAO,EAAe,eAAe,EAAE,MAAM,mBAAmB,CAAA;AAChE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAC/D,OAAO,KAAK,EAEV,WAAW,EAEX,KAAK,EAEN,MAAM,sBAAsB,CAAA;AAC7B,OAAO,EAAqC,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AAE1F,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAGL,MAAM,EAKN,MAAM,EAGP,MAAM,yBAAyB,CAAA;AAChC,OAAO,KAAK,KAAK,IAAI,MAAM,oBAAoB,CAAA;AAC/C,OAAO,KAAK,MAAM,OAAO,CAAA;AAIzB,MAAM,WAAW,sBAAsB;IACrC,MAAM,EAAE,eAAe,CAAA;IACvB;;;;;;;;;OASG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,IAAI,CAAC,EAAE,CACL,KAAK,EAAE,KAAK,CAAC,eAAe,CAAC,EAC7B,GAAG,EAAE;QAAE,gBAAgB,EAAE,gBAAgB,CAAC;QAAC,UAAU,EAAE,IAAI,CAAC,IAAI,CAAA;KAAE,KAC/D,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,UAAU,CAAC,UAAU,CAAC,CAAA;IAC/E,WAAW,CAAC,EAAE,OAAO,CAAC,WAAW,CAAC,CAAA;IAClC,aAAa,CAAC,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK,KAAK,CAAC,SAAS,CAAA;IACvD,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,eAAe,GAAG,OAAO,KAAK,KAAK,CAAC,SAAS,CAAA;IACnE,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,wBAAwB,GAAG,gBAAgB,GAAG,SAAS,KAAK,KAAK,CAAC,SAAS,CAAA;IACpG,OAAO,EAAE,OAAO,CAAA;IAChB;;;;;;;;;;;OAWG;IACH,YAAY,EAAE,CAAC,GAAG,EAAE,MAAM,IAAI,KAAK,IAAI,CAAA;IACvC,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB;;;;;OAKG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC,SAAS,CAAA;IAC9B,KAAK,CAAC,EAAE;QACN,UAAU,CAAC,EAAE,MAAM,CAAA;KACpB,CAAA;CACF;AA2BD,eAAO,MAAM,iBAAiB,GAAI,0LAgB/B,sBAAsB,GAAG,KAAK,CAAC,iBAAiB,KAAG,KAAK,CAAC,SAoC3D,CAAA"}
|