@livestore/react 0.1.0 → 0.2.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.
@@ -1,131 +0,0 @@
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 useScopedQuery = <TResult>(makeQuery: () => LiveQuery<TResult>, key: DepKey): TResult =>
35
- useScopedQueryRef(makeQuery, key).current
36
-
37
- export const useScopedQueryRef = <TResult>(
38
- makeQuery: () => LiveQuery<TResult>,
39
- key: DepKey,
40
- ): React.MutableRefObject<TResult> => {
41
- const { query$ } = useMakeScopedQuery(makeQuery, key)
42
-
43
- return useQueryRef(query$)
44
- }
45
-
46
- export const useMakeScopedQuery = <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:useScopedQuery:${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
- }