@livestore/react 0.0.0-snapshot-8d3edf87cb1e88c7b67c5f3ea9d0b307253c33df

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 (87) hide show
  1. package/README.md +1 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/LiveStoreContext.d.ts +7 -0
  4. package/dist/LiveStoreContext.d.ts.map +1 -0
  5. package/dist/LiveStoreContext.js +13 -0
  6. package/dist/LiveStoreContext.js.map +1 -0
  7. package/dist/LiveStoreProvider.d.ts +49 -0
  8. package/dist/LiveStoreProvider.d.ts.map +1 -0
  9. package/dist/LiveStoreProvider.js +168 -0
  10. package/dist/LiveStoreProvider.js.map +1 -0
  11. package/dist/LiveStoreProvider.test.d.ts +2 -0
  12. package/dist/LiveStoreProvider.test.d.ts.map +1 -0
  13. package/dist/LiveStoreProvider.test.js +62 -0
  14. package/dist/LiveStoreProvider.test.js.map +1 -0
  15. package/dist/__tests__/fixture.d.ts +567 -0
  16. package/dist/__tests__/fixture.d.ts.map +1 -0
  17. package/dist/__tests__/fixture.js +61 -0
  18. package/dist/__tests__/fixture.js.map +1 -0
  19. package/dist/experimental/components/LiveList.d.ts +21 -0
  20. package/dist/experimental/components/LiveList.d.ts.map +1 -0
  21. package/dist/experimental/components/LiveList.js +31 -0
  22. package/dist/experimental/components/LiveList.js.map +1 -0
  23. package/dist/experimental/mod.d.ts +2 -0
  24. package/dist/experimental/mod.d.ts.map +1 -0
  25. package/dist/experimental/mod.js +2 -0
  26. package/dist/experimental/mod.js.map +1 -0
  27. package/dist/mod.d.ts +8 -0
  28. package/dist/mod.d.ts.map +1 -0
  29. package/dist/mod.js +8 -0
  30. package/dist/mod.js.map +1 -0
  31. package/dist/useAtom.d.ts +10 -0
  32. package/dist/useAtom.d.ts.map +1 -0
  33. package/dist/useAtom.js +37 -0
  34. package/dist/useAtom.js.map +1 -0
  35. package/dist/useQuery.d.ts +9 -0
  36. package/dist/useQuery.d.ts.map +1 -0
  37. package/dist/useQuery.js +88 -0
  38. package/dist/useQuery.js.map +1 -0
  39. package/dist/useQuery.test.d.ts +2 -0
  40. package/dist/useQuery.test.d.ts.map +1 -0
  41. package/dist/useQuery.test.js +51 -0
  42. package/dist/useQuery.test.js.map +1 -0
  43. package/dist/useRow.d.ts +46 -0
  44. package/dist/useRow.d.ts.map +1 -0
  45. package/dist/useRow.js +96 -0
  46. package/dist/useRow.js.map +1 -0
  47. package/dist/useRow.test.d.ts +2 -0
  48. package/dist/useRow.test.d.ts.map +1 -0
  49. package/dist/useRow.test.js +212 -0
  50. package/dist/useRow.test.js.map +1 -0
  51. package/dist/useTemporaryQuery.d.ts +22 -0
  52. package/dist/useTemporaryQuery.d.ts.map +1 -0
  53. package/dist/useTemporaryQuery.js +75 -0
  54. package/dist/useTemporaryQuery.js.map +1 -0
  55. package/dist/useTemporaryQuery.test.d.ts +2 -0
  56. package/dist/useTemporaryQuery.test.d.ts.map +1 -0
  57. package/dist/useTemporaryQuery.test.js +59 -0
  58. package/dist/useTemporaryQuery.test.js.map +1 -0
  59. package/dist/utils/stack-info.d.ts +4 -0
  60. package/dist/utils/stack-info.d.ts.map +1 -0
  61. package/dist/utils/stack-info.js +11 -0
  62. package/dist/utils/stack-info.js.map +1 -0
  63. package/dist/utils/useStateRefWithReactiveInput.d.ts +13 -0
  64. package/dist/utils/useStateRefWithReactiveInput.d.ts.map +1 -0
  65. package/dist/utils/useStateRefWithReactiveInput.js +38 -0
  66. package/dist/utils/useStateRefWithReactiveInput.js.map +1 -0
  67. package/package.json +54 -0
  68. package/src/LiveStoreContext.ts +19 -0
  69. package/src/LiveStoreProvider.test.tsx +109 -0
  70. package/src/LiveStoreProvider.tsx +295 -0
  71. package/src/__snapshots__/useRow.test.tsx.snap +359 -0
  72. package/src/__tests__/fixture.tsx +119 -0
  73. package/src/ambient.d.ts +2 -0
  74. package/src/experimental/components/LiveList.tsx +84 -0
  75. package/src/experimental/mod.ts +1 -0
  76. package/src/mod.ts +13 -0
  77. package/src/useAtom.ts +55 -0
  78. package/src/useQuery.test.tsx +82 -0
  79. package/src/useQuery.ts +122 -0
  80. package/src/useRow.test.tsx +346 -0
  81. package/src/useRow.ts +182 -0
  82. package/src/useTemporaryQuery.test.tsx +98 -0
  83. package/src/useTemporaryQuery.ts +131 -0
  84. package/src/utils/stack-info.ts +13 -0
  85. package/src/utils/useStateRefWithReactiveInput.ts +51 -0
  86. package/tsconfig.json +20 -0
  87. package/vitest.config.js +17 -0
package/src/useRow.ts ADDED
@@ -0,0 +1,182 @@
1
+ import type { QueryInfo } from '@livestore/common'
2
+ import { SessionIdSymbol } from '@livestore/common'
3
+ import { DbSchema } from '@livestore/common/schema'
4
+ import type { SqliteDsl } from '@livestore/db-schema'
5
+ import type { LiveQuery, ReactivityGraph, RowResult } from '@livestore/livestore'
6
+ import { rowQuery } from '@livestore/livestore'
7
+ import { shouldNeverHappen } from '@livestore/utils'
8
+ import { ReadonlyRecord } from '@livestore/utils/effect'
9
+ import React from 'react'
10
+
11
+ import { useStore } from './LiveStoreContext.js'
12
+ import { useQueryRef } from './useQuery.js'
13
+ import { useMakeTemporaryQuery } from './useTemporaryQuery.js'
14
+
15
+ export type UseRowResult<TTableDef extends DbSchema.TableDef> = [
16
+ row: RowResult<TTableDef>,
17
+ setRow: StateSetters<TTableDef>,
18
+ query$: LiveQuery<RowResult<TTableDef>, QueryInfo>,
19
+ ]
20
+
21
+ export type UseRowOptionsDefaulValues<TTableDef extends DbSchema.TableDef> = {
22
+ defaultValues?: Partial<RowResult<TTableDef>>
23
+ }
24
+
25
+ export type UseRowOptionsBase = {
26
+ reactivityGraph?: ReactivityGraph
27
+ }
28
+
29
+ /**
30
+ * Similar to `React.useState` but returns a tuple of `[row, setRow, query$]` for a given table where ...
31
+ *
32
+ * - `row` is the current value of the row (fully decoded according to the table schema)
33
+ * - `setRow` is a function that can be used to update the row (values will be encoded according to the table schema)
34
+ * - `query$` is a `LiveQuery` that e.g. can be used to subscribe to changes to the row
35
+ *
36
+ * If the table is a singleton table, `useRow` can be called without an `id` argument. Otherwise, the `id` argument is required.
37
+ */
38
+ export const useRow: {
39
+ <
40
+ TTableDef extends DbSchema.TableDef<
41
+ DbSchema.DefaultSqliteTableDef,
42
+ boolean,
43
+ DbSchema.TableOptions & { isSingleton: true; deriveMutations: { enabled: true } }
44
+ >,
45
+ >(
46
+ table: TTableDef,
47
+ options?: UseRowOptionsBase,
48
+ ): UseRowResult<TTableDef>
49
+ <
50
+ TTableDef extends DbSchema.TableDef<
51
+ DbSchema.DefaultSqliteTableDef,
52
+ boolean,
53
+ DbSchema.TableOptions & { isSingleton: false; deriveMutations: { enabled: true } }
54
+ >,
55
+ >(
56
+ table: TTableDef,
57
+ // TODO adjust so it works with arbitrary primary keys or unique constraints
58
+ id: string | SessionIdSymbol,
59
+ options?: UseRowOptionsBase & UseRowOptionsDefaulValues<TTableDef>,
60
+ ): UseRowResult<TTableDef>
61
+ } = <
62
+ TTableDef extends DbSchema.TableDef<
63
+ DbSchema.DefaultSqliteTableDefConstrained,
64
+ boolean,
65
+ DbSchema.TableOptions & { deriveMutations: { enabled: true } }
66
+ >,
67
+ >(
68
+ table: TTableDef,
69
+ idOrOptions?: string | SessionIdSymbol | UseRowOptionsBase,
70
+ options_?: UseRowOptionsBase & UseRowOptionsDefaulValues<TTableDef>,
71
+ ): UseRowResult<TTableDef> => {
72
+ const sqliteTableDef = table.sqliteDef
73
+ const id = typeof idOrOptions === 'string' || idOrOptions === SessionIdSymbol ? idOrOptions : undefined
74
+ const options: (UseRowOptionsBase & UseRowOptionsDefaulValues<TTableDef>) | undefined =
75
+ typeof idOrOptions === 'string' || idOrOptions === SessionIdSymbol ? options_ : idOrOptions
76
+ const { defaultValues, reactivityGraph } = options ?? {}
77
+
78
+ type TComponentState = SqliteDsl.FromColumns.RowDecoded<TTableDef['sqliteDef']['columns']>
79
+
80
+ const tableName = table.sqliteDef.name
81
+
82
+ if (DbSchema.tableHasDerivedMutations(table) === false) {
83
+ shouldNeverHappen(`useRow called on table "${tableName}" which does not have 'deriveMutations: true' set`)
84
+ }
85
+
86
+ const { store } = useStore()
87
+
88
+ if (
89
+ store.schema.tables.has(table.sqliteDef.name) === false &&
90
+ table.sqliteDef.name.startsWith('__livestore') === false
91
+ ) {
92
+ shouldNeverHappen(`Table "${table.sqliteDef.name}" not found in schema`)
93
+ }
94
+
95
+ // console.debug('useRow', tableName, id)
96
+
97
+ const idStr = id === SessionIdSymbol ? 'session' : id
98
+
99
+ const { query$, otelContext } = useMakeTemporaryQuery(
100
+ (otelContext) =>
101
+ DbSchema.tableIsSingleton(table)
102
+ ? (rowQuery(table, { otelContext, reactivityGraph }) as LiveQuery<RowResult<TTableDef>, QueryInfo>)
103
+ : (rowQuery(table as TTableDef & { options: { isSingleton: false } }, id!, {
104
+ otelContext,
105
+ defaultValues: defaultValues!,
106
+ reactivityGraph,
107
+ }) as any as LiveQuery<RowResult<TTableDef>, QueryInfo>),
108
+ [idStr!, tableName],
109
+ {
110
+ otel: {
111
+ spanName: `LiveStore:useRow:${tableName}${idStr === undefined ? '' : `:${idStr}`}`,
112
+ attributes: { id: idStr },
113
+ },
114
+ },
115
+ )
116
+
117
+ const query$Ref = useQueryRef(query$, otelContext) as React.MutableRefObject<RowResult<TTableDef>>
118
+
119
+ const setState = React.useMemo<StateSetters<TTableDef>>(() => {
120
+ if (table.isSingleColumn) {
121
+ return (newValueOrFn: RowResult<TTableDef>) => {
122
+ const newValue = typeof newValueOrFn === 'function' ? newValueOrFn(query$Ref.current) : newValueOrFn
123
+ if (query$Ref.current === newValue) return
124
+
125
+ // NOTE we need to account for the short-hand syntax for single-column+singleton tables
126
+ if (table.options.isSingleton) {
127
+ store.mutate(table.update(newValue))
128
+ } else {
129
+ store.mutate(table.update({ where: { id }, values: { value: newValue } }))
130
+ }
131
+ // store.mutate(updateMutationForQueryInfo(query$.queryInfo!, { value: newValue }))
132
+ }
133
+ } else {
134
+ const setState = // TODO: do we have a better type for the values that can go in SQLite?
135
+ ReadonlyRecord.map(sqliteTableDef.columns, (column, columnName) => (newValueOrFn: any) => {
136
+ const newValue =
137
+ // @ts-expect-error TODO fix typing
138
+ typeof newValueOrFn === 'function' ? newValueOrFn(query$Ref.current[columnName]) : newValueOrFn
139
+
140
+ // Don't update the state if it's the same as the value already seen in the component
141
+ // @ts-expect-error TODO fix typing
142
+ if (query$Ref.current[columnName] === newValue) return
143
+
144
+ store.mutate(table.update({ where: { id: id ?? 'singleton' }, values: { [columnName]: newValue } }))
145
+ // store.mutate(updateMutationForQueryInfo(query$.queryInfo!, { [columnName]: newValue }))
146
+ })
147
+
148
+ setState.setMany = (columnValuesOrFn: Partial<TComponentState>) => {
149
+ const columnValues =
150
+ // @ts-expect-error TODO fix typing
151
+ typeof columnValuesOrFn === 'function' ? columnValuesOrFn(query$Ref.current) : columnValuesOrFn
152
+
153
+ // TODO use hashing instead
154
+ // Don't update the state if it's the same as the value already seen in the component
155
+ if (
156
+ // @ts-expect-error TODO fix typing
157
+ Object.entries(columnValues).every(([columnName, value]) => query$Ref.current[columnName] === value)
158
+ ) {
159
+ return
160
+ }
161
+
162
+ store.mutate(table.update({ where: { id: id ?? 'singleton' }, values: columnValues }))
163
+ // store.mutate(updateMutationForQueryInfo(query$.queryInfo!, columnValues))
164
+ }
165
+
166
+ return setState as any
167
+ }
168
+ }, [id, query$Ref, sqliteTableDef.columns, store, table])
169
+
170
+ return [query$Ref.current, setState, query$]
171
+ }
172
+
173
+ export type Dispatch<A> = (action: A) => void
174
+ export type SetStateAction<S> = S | ((previousValue: S) => S)
175
+
176
+ export type StateSetters<TTableDef extends DbSchema.TableDef> = TTableDef['isSingleColumn'] extends true
177
+ ? Dispatch<SetStateAction<RowResult<TTableDef>>>
178
+ : {
179
+ [K in keyof RowResult<TTableDef>]: Dispatch<SetStateAction<RowResult<TTableDef>[K]>>
180
+ } & {
181
+ setMany: Dispatch<SetStateAction<Partial<RowResult<TTableDef>>>>
182
+ }
@@ -0,0 +1,98 @@
1
+ import * as LiveStore from '@livestore/livestore'
2
+ import { querySQL } from '@livestore/livestore'
3
+ import { Effect, Schema } from '@livestore/utils/effect'
4
+ import { render, renderHook } from '@testing-library/react'
5
+ import React from 'react'
6
+ // @ts-expect-error no types
7
+ import * as ReactWindow from 'react-window'
8
+ import { describe, expect, it } from 'vitest'
9
+
10
+ import { makeTodoMvcReact, tables, todos } from './__tests__/fixture.js'
11
+ import * as LiveStoreReact from './mod.js'
12
+
13
+ describe('useTemporaryQuery', () => {
14
+ it('simple', () =>
15
+ Effect.gen(function* () {
16
+ const { wrapper, store, makeRenderCount } = yield* makeTodoMvcReact()
17
+
18
+ const renderCount = makeRenderCount()
19
+
20
+ store.mutate(
21
+ todos.insert({ id: 't1', text: 'buy milk', completed: false }),
22
+ todos.insert({ id: 't2', text: 'buy bread', completed: false }),
23
+ )
24
+
25
+ const queryMap = new Map<string, LiveStore.LiveQuery<any>>()
26
+
27
+ const { rerender, result, unmount } = renderHook(
28
+ (id: string) => {
29
+ renderCount.inc()
30
+
31
+ return LiveStoreReact.useTemporaryQuery(() => {
32
+ const query$ = querySQL(`select * from todos where id = '${id}'`, {
33
+ schema: Schema.Array(tables.todos.schema),
34
+ })
35
+ queryMap.set(id, query$)
36
+ return query$
37
+ }, id)
38
+ },
39
+ { wrapper, initialProps: 't1' },
40
+ )
41
+
42
+ expect(result.current.length).toBe(1)
43
+ expect(result.current[0]!.text).toBe('buy milk')
44
+ expect(renderCount.val).toBe(1)
45
+ expect(queryMap.get('t1')!.runs).toBe(1)
46
+
47
+ rerender('t2')
48
+
49
+ expect(result.current.length).toBe(1)
50
+ expect(result.current[0]!.text).toBe('buy bread')
51
+ expect(renderCount.val).toBe(2)
52
+ expect(queryMap.get('t1')!.runs).toBe(1)
53
+ expect(queryMap.get('t2')!.runs).toBe(1)
54
+
55
+ unmount()
56
+
57
+ expect(queryMap.get('t2')!.runs).toBe(1)
58
+ }).pipe(Effect.scoped, Effect.tapCauseLogPretty, Effect.runPromise))
59
+
60
+ // NOTE this test covers some special react lifecyle paths which I couldn't easily reproduce without react-window
61
+ // it basically causes a "query swap" in the `useMemo` and both a `useEffect` cleanup call.
62
+ // To handle this properly we introduced the `_tag: 'destroyed'` state in the `spanAlreadyStartedCache`.
63
+ it('should work for a list with react-window', () =>
64
+ Effect.gen(function* () {
65
+ const { wrapper } = yield* makeTodoMvcReact()
66
+
67
+ const ListWrapper: React.FC<{ numItems: number }> = ({ numItems }) => {
68
+ return (
69
+ <ReactWindow.FixedSizeList
70
+ height={100}
71
+ width={100}
72
+ itemSize={10}
73
+ itemCount={numItems}
74
+ itemData={Array.from({ length: numItems }, (_, i) => i).reverse()}
75
+ >
76
+ {ListItem}
77
+ </ReactWindow.FixedSizeList>
78
+ )
79
+ }
80
+
81
+ const ListItem: React.FC<{ data: ReadonlyArray<number>; index: number }> = ({ data: ids, index }) => {
82
+ const id = ids[index]!
83
+ const res = LiveStoreReact.useTemporaryQuery(
84
+ () => LiveStore.computed(() => id, { label: `ListItem.${id}` }),
85
+ id,
86
+ )
87
+ return <div role="listitem">{res}</div>
88
+ }
89
+
90
+ const renderResult = render(<ListWrapper numItems={1} />, { wrapper })
91
+
92
+ expect(renderResult.container.textContent).toBe('0')
93
+
94
+ renderResult.rerender(<ListWrapper numItems={2} />)
95
+
96
+ expect(renderResult.container.textContent).toBe('10')
97
+ }).pipe(Effect.scoped, Effect.tapCauseLogPretty, Effect.runPromise))
98
+ })
@@ -0,0 +1,131 @@
1
+ import type { QueryInfo } from '@livestore/common'
2
+ import type { LiveQuery } from '@livestore/livestore'
3
+ import * as otel from '@opentelemetry/api'
4
+ import React from 'react'
5
+
6
+ import { useStore } from './LiveStoreContext.js'
7
+ import { useQueryRef } from './useQuery.js'
8
+
9
+ // NOTE Given `useMemo` will be called multiple times (e.g. when using React Strict mode or Fast Refresh),
10
+ // we are using this cache to avoid starting multiple queries/spans for the same component.
11
+ // This is somewhat against some recommended React best practices, but it should be fine in our case below.
12
+ // Please definitely open an issue if you see or run into any problems with this approach!
13
+ const cache = new Map<
14
+ string,
15
+ | {
16
+ _tag: 'active'
17
+ rc: number
18
+ query$: LiveQuery<any, any>
19
+ span: otel.Span
20
+ otelContext: otel.Context
21
+ }
22
+ | {
23
+ _tag: 'destroyed'
24
+ }
25
+ >()
26
+
27
+ export type DepKey = string | number | ReadonlyArray<string | number>
28
+
29
+ /**
30
+ * Creates a query, subscribes and destroys it when the component unmounts.
31
+ *
32
+ * The `key` is used to determine whether the a new query should be created or if the existing one should be reused.
33
+ */
34
+ export const useTemporaryQuery = <TResult>(makeQuery: () => LiveQuery<TResult>, key: DepKey): TResult =>
35
+ useTemporaryQueryRef(makeQuery, key).current
36
+
37
+ export const useTemporaryQueryRef = <TResult>(
38
+ makeQuery: () => LiveQuery<TResult>,
39
+ key: DepKey,
40
+ ): React.MutableRefObject<TResult> => {
41
+ const { query$ } = useMakeTemporaryQuery(makeQuery, key)
42
+
43
+ return useQueryRef(query$)
44
+ }
45
+
46
+ export const useMakeTemporaryQuery = <TResult, TQueryInfo extends QueryInfo>(
47
+ makeQuery: (otelContext: otel.Context) => LiveQuery<TResult, TQueryInfo>,
48
+ key: DepKey,
49
+ options?: {
50
+ otel?: {
51
+ spanName?: string
52
+ attributes?: otel.Attributes
53
+ }
54
+ },
55
+ ): { query$: LiveQuery<TResult, TQueryInfo>; otelContext: otel.Context } => {
56
+ const { store } = useStore()
57
+ const fullKey = React.useMemo(
58
+ // NOTE We're using the `makeQuery` function body string to make sure the key is unique across the app
59
+ // TODO we should figure out whether this could cause some problems and/or if there's a better way to do this
60
+ () => (Array.isArray(key) ? key.join('-') : key) + '-' + store.reactivityGraph.id + '-' + makeQuery.toString(),
61
+ [key, makeQuery, store.reactivityGraph.id],
62
+ )
63
+ const fullKeyRef = React.useRef<string>()
64
+
65
+ const { query$, otelContext } = React.useMemo(() => {
66
+ if (fullKeyRef.current !== undefined && fullKeyRef.current !== fullKey) {
67
+ // console.debug('fullKey changed', 'prev', fullKeyRef.current.split('-')[0]!, '-> new', fullKey.split('-')[0]!)
68
+
69
+ const cachedItem = cache.get(fullKeyRef.current)
70
+ if (cachedItem !== undefined && cachedItem._tag === 'active') {
71
+ cachedItem.rc--
72
+
73
+ if (cachedItem.rc === 0) {
74
+ // console.debug('rc=0-changed', cachedItem.query$.id, cachedItem.query$.label)
75
+ cachedItem.query$.destroy()
76
+ cachedItem.span.end()
77
+ cache.set(fullKeyRef.current, { _tag: 'destroyed' })
78
+ }
79
+ }
80
+ }
81
+
82
+ const cachedItem = cache.get(fullKey)
83
+ if (cachedItem !== undefined && cachedItem._tag === 'active') {
84
+ // console.debug('rc++', cachedItem.query$.id, cachedItem.query$.label)
85
+ cachedItem.rc++
86
+
87
+ return cachedItem
88
+ }
89
+
90
+ const spanName = options?.otel?.spanName ?? `LiveStore:useTemporaryQuery:${key}`
91
+
92
+ const span = store.otel.tracer.startSpan(
93
+ spanName,
94
+ { attributes: options?.otel?.attributes },
95
+ store.otel.queriesSpanContext,
96
+ )
97
+
98
+ const otelContext = otel.trace.setSpan(otel.context.active(), span)
99
+
100
+ const query$ = makeQuery(otelContext)
101
+
102
+ cache.set(fullKey, { _tag: 'active', rc: 1, query$, span, otelContext })
103
+
104
+ return { query$, otelContext }
105
+ // eslint-disable-next-line react-hooks/exhaustive-deps
106
+ }, [fullKey])
107
+
108
+ fullKeyRef.current = fullKey
109
+
110
+ React.useEffect(() => {
111
+ return () => {
112
+ const fullKey = fullKeyRef.current!
113
+ const cachedItem = cache.get(fullKey)
114
+ // NOTE in case the fullKey changed then the query was already destroyed in the useMemo above
115
+ if (cachedItem === undefined || cachedItem._tag === 'destroyed') return
116
+
117
+ // console.debug('rc--', cachedItem.query$.id, cachedItem.query$.label)
118
+
119
+ cachedItem.rc--
120
+
121
+ if (cachedItem.rc === 0) {
122
+ // console.debug('rc=0', cachedItem.query$.id, cachedItem.query$.label)
123
+ cachedItem.query$.destroy()
124
+ cachedItem.span.end()
125
+ cache.delete(fullKey)
126
+ }
127
+ }
128
+ }, [])
129
+
130
+ return { query$, otelContext }
131
+ }
@@ -0,0 +1,13 @@
1
+ import { extractStackInfoFromStackTrace, type StackInfo } from '@livestore/livestore'
2
+ import React from 'react'
3
+
4
+ export const originalStackLimit = Error.stackTraceLimit
5
+
6
+ export const useStackInfo = (): StackInfo =>
7
+ React.useMemo(() => {
8
+ Error.stackTraceLimit = 10
9
+ // eslint-disable-next-line unicorn/error-message
10
+ const stack = new Error().stack!
11
+ Error.stackTraceLimit = originalStackLimit
12
+ return extractStackInfoFromStackTrace(stack)
13
+ }, [])
@@ -0,0 +1,51 @@
1
+ import React from 'react'
2
+
3
+ /**
4
+ * A variant of `React.useState` which allows the `inputState` to change over time as well.
5
+ * Important: This hook is synchronous / single-render-pass (i.e. doesn't use `useEffect` or `setState` directly).
6
+ *
7
+ * Notes:
8
+ * - The output state is always reset to the input state in case the input state changes (i.e. the previous "external" `setStateAndRerender` call is forgotten)
9
+ * - This hook might not work properly with React Suspense
10
+ * - Also see this Tweet for more potential problems: https://twitter.com/schickling/status/1677317711104278528
11
+ *
12
+ */
13
+ export const useStateRefWithReactiveInput = <T>(
14
+ inputState: T,
15
+ ): [React.MutableRefObject<T>, (newState: T | ((prev: T) => T)) => void] => {
16
+ const [_, rerender] = React.useState(0)
17
+
18
+ const lastKnownInputStateRef = React.useRef<T>(inputState)
19
+ const stateRef = React.useRef<T>(inputState)
20
+
21
+ if (lastKnownInputStateRef.current !== inputState) {
22
+ lastKnownInputStateRef.current = inputState
23
+
24
+ // NOTE we don't need to re-render here, because the component is already re-rendering due to the `inputState` change
25
+ stateRef.current = inputState
26
+ }
27
+
28
+ const setStateAndRerender = React.useCallback(
29
+ (newState: ((prev: T) => T) | T) => {
30
+ // @ts-expect-error https://github.com/microsoft/TypeScript/issues/37663
31
+ const val = typeof newState === 'function' ? newState(stateRef.current) : newState
32
+ stateRef.current = val
33
+ rerender((c) => c + 1)
34
+ },
35
+ [rerender],
36
+ )
37
+
38
+ return [stateRef, setStateAndRerender]
39
+ }
40
+
41
+ // Down-side of this implementation: Double render pass due to `setState` call (which forces a re-render)
42
+ // Keeping around for now in case `useStateRefWithReactiveInput` doesn't work out
43
+ // const _useStateWithReactiveInput = <T>(inputState: T): [T, (newState: T | ((prev: T) => T)) => void] => {
44
+ // const [externalState, setExternalState] = React.useState(inputState)
45
+
46
+ // if (externalState !== inputState) {
47
+ // setExternalState(inputState)
48
+ // }
49
+
50
+ // return [externalState, setExternalState]
51
+ // }
package/tsconfig.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "extends": "../../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src",
6
+ "jsx": "react",
7
+ "skipLibCheck": true,
8
+ "resolveJsonModule": true,
9
+ // "jsx": "preserve",
10
+ "tsBuildInfoFile": "./dist/.tsbuildinfo"
11
+ },
12
+ "include": ["./src"],
13
+ "references": [
14
+ { "path": "../db-schema" },
15
+ { "path": "../common" },
16
+ { "path": "../web" },
17
+ { "path": "../livestore" },
18
+ { "path": "../utils" }
19
+ ]
20
+ }
@@ -0,0 +1,17 @@
1
+ import { defineConfig } from 'vite'
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ // Needed for React hook tests
6
+ environment: 'jsdom',
7
+ },
8
+ esbuild: {
9
+ // TODO remove once `using` keyword supported OOTB with Vite https://github.com/vitejs/vite/issues/15464#issuecomment-1872485703
10
+ target: 'es2020',
11
+ },
12
+ resolve: {
13
+ alias: {
14
+ '@livestore/wa-sqlite/dist/wa-sqlite.mjs': '@livestore/wa-sqlite/dist/wa-sqlite.node.mjs',
15
+ },
16
+ },
17
+ })