@powersync/react 2.0.1 → 2.1.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 (69) hide show
  1. package/README.md +15 -0
  2. package/lib/hooks/PowerSyncContext.d.ts +4 -2
  3. package/lib/hooks/PowerSyncContext.js +7 -1
  4. package/lib/hooks/PowerSyncContext.js.map +1 -1
  5. package/lib/hooks/streams.d.ts +4 -3
  6. package/lib/hooks/streams.js +11 -10
  7. package/lib/hooks/streams.js.map +1 -1
  8. package/lib/hooks/suspense/SuspenseQueryCache.d.ts +46 -0
  9. package/lib/hooks/suspense/SuspenseQueryCache.js +231 -0
  10. package/lib/hooks/suspense/SuspenseQueryCache.js.map +1 -0
  11. package/lib/hooks/suspense/useSuspenseQuery.d.ts +3 -3
  12. package/lib/hooks/suspense/useSuspenseQuery.js +28 -7
  13. package/lib/hooks/suspense/useSuspenseQuery.js.map +1 -1
  14. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js +60 -24
  15. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js.map +1 -1
  16. package/lib/hooks/useStatus.d.ts +7 -1
  17. package/lib/hooks/useStatus.js +11 -6
  18. package/lib/hooks/useStatus.js.map +1 -1
  19. package/lib/hooks/watched/QueryRunner.d.ts +90 -0
  20. package/lib/hooks/watched/QueryRunner.js +366 -0
  21. package/lib/hooks/watched/QueryRunner.js.map +1 -0
  22. package/lib/hooks/watched/useQuery.js +14 -40
  23. package/lib/hooks/watched/useQuery.js.map +1 -1
  24. package/lib/hooks/watched/useWatchedQuerySubscription.d.ts +1 -1
  25. package/lib/hooks/watched/useWatchedQuerySubscription.js.map +1 -1
  26. package/lib/hooks/watched/watch-types.d.ts +39 -3
  27. package/lib/hooks/watched/watch-utils.d.ts +3 -15
  28. package/lib/hooks/watched/watch-utils.js +5 -31
  29. package/lib/hooks/watched/watch-utils.js.map +1 -1
  30. package/lib/index.d.ts +2 -2
  31. package/lib/index.js +1 -1
  32. package/lib/index.js.map +1 -1
  33. package/package.json +11 -9
  34. package/src/hooks/PowerSyncContext.ts +9 -3
  35. package/src/hooks/streams.ts +14 -20
  36. package/src/hooks/suspense/SuspenseQueryCache.ts +253 -0
  37. package/src/hooks/suspense/useSuspenseQuery.ts +40 -13
  38. package/src/hooks/suspense/useWatchedQuerySuspenseSubscription.ts +65 -25
  39. package/src/hooks/useStatus.ts +21 -7
  40. package/src/hooks/watched/QueryRunner.ts +484 -0
  41. package/src/hooks/watched/useQuery.ts +15 -41
  42. package/src/hooks/watched/useWatchedQuerySubscription.ts +2 -2
  43. package/src/hooks/watched/watch-types.ts +42 -3
  44. package/src/hooks/watched/watch-utils.ts +8 -54
  45. package/src/index.ts +8 -2
  46. package/lib/QueryStore.d.ts +0 -10
  47. package/lib/QueryStore.js +0 -63
  48. package/lib/QueryStore.js.map +0 -1
  49. package/lib/hooks/suspense/suspense-utils.d.ts +0 -16
  50. package/lib/hooks/suspense/suspense-utils.js +0 -76
  51. package/lib/hooks/suspense/suspense-utils.js.map +0 -1
  52. package/lib/hooks/suspense/useSingleSuspenseQuery.d.ts +0 -10
  53. package/lib/hooks/suspense/useSingleSuspenseQuery.js +0 -73
  54. package/lib/hooks/suspense/useSingleSuspenseQuery.js.map +0 -1
  55. package/lib/hooks/suspense/useWatchedSuspenseQuery.d.ts +0 -6
  56. package/lib/hooks/suspense/useWatchedSuspenseQuery.js +0 -26
  57. package/lib/hooks/suspense/useWatchedSuspenseQuery.js.map +0 -1
  58. package/lib/hooks/watched/useSingleQuery.d.ts +0 -6
  59. package/lib/hooks/watched/useSingleQuery.js +0 -59
  60. package/lib/hooks/watched/useSingleQuery.js.map +0 -1
  61. package/lib/hooks/watched/useWatchedQuery.d.ts +0 -13
  62. package/lib/hooks/watched/useWatchedQuery.js +0 -81
  63. package/lib/hooks/watched/useWatchedQuery.js.map +0 -1
  64. package/src/QueryStore.ts +0 -81
  65. package/src/hooks/suspense/suspense-utils.ts +0 -86
  66. package/src/hooks/suspense/useSingleSuspenseQuery.ts +0 -81
  67. package/src/hooks/suspense/useWatchedSuspenseQuery.ts +0 -36
  68. package/src/hooks/watched/useSingleQuery.ts +0 -67
  69. package/src/hooks/watched/useWatchedQuery.ts +0 -93
package/README.md CHANGED
@@ -121,6 +121,21 @@ export const TodoListsDisplayDemo = () => {
121
121
 
122
122
  ```
123
123
 
124
+ When the SQL or parameters passed to `useQuery` change, the hook keeps returning the previous query's rows, with `isFetching` set to `true`, until the updated query has produced its first result. A refetch caused by a change to one of the queried tables reports `isFetching` in the same way. While `isFetching` is `true`, `fetchReason` says why: `'initial'` for the first load, `'tables-changed'` for a refetch of the same query, and `'settings-changed'` while the rows still belong to the previous query. It is `undefined` when nothing is being fetched.
125
+
126
+ ```JSX
127
+ const { data: todos, fetchReason } = useQuery('SELECT * FROM todos WHERE list_id = ?', [listId]);
128
+ const showingPreviousList = fetchReason === 'settings-changed';
129
+
130
+ return (
131
+ <ul style={{ opacity: showingPreviousList ? 0.5 : 1 }}>
132
+ {todos.map((todo) => (
133
+ <li key={todo.id}>{todo.description}</li>
134
+ ))}
135
+ </ul>
136
+ );
137
+ ```
138
+
124
139
  ### Suspense
125
140
 
126
141
  The `useSuspenseQuery` hook also allows you to access the results of a watched query, but its loading and fetching states are handled through [Suspense](https://react.dev/reference/react/Suspense). Unlike `useQuery`, the hook doesn't return `isLoading` or `isFetching` for the loading states nor `error` for the error state. These should be handled with variants of `<Suspense>` and `<ErrorBoundary>` respectively.
@@ -1,5 +1,6 @@
1
+ import { CommonPowerSyncDatabase } from '@powersync/common';
1
2
  import React from 'react';
2
- export declare const PowerSyncContext: React.Context<import("@powersync/common").CommonPowerSyncDatabase>;
3
+ export declare const PowerSyncContext: React.Context<CommonPowerSyncDatabase | null>;
3
4
  /**
4
5
  * Custom hook that provides access to the PowerSync context.
5
6
  * @returns The PowerSync Database instance.
@@ -17,4 +18,5 @@ export declare const PowerSyncContext: React.Context<import("@powersync/common")
17
18
  * </ul>
18
19
  * };
19
20
  */
20
- export declare const usePowerSync: () => import("@powersync/common").CommonPowerSyncDatabase;
21
+ export declare function usePowerSync(): CommonPowerSyncDatabase;
22
+ export declare const usePowerSyncOrNull: () => CommonPowerSyncDatabase | null;
@@ -17,5 +17,11 @@ export const PowerSyncContext = React.createContext(null);
17
17
  * </ul>
18
18
  * };
19
19
  */
20
- export const usePowerSync = () => React.useContext(PowerSyncContext);
20
+ export function usePowerSync() {
21
+ const db = usePowerSyncOrNull();
22
+ if (db == null)
23
+ throw new Error('PowerSync not configured.');
24
+ return db;
25
+ }
26
+ export const usePowerSyncOrNull = () => React.useContext(PowerSyncContext);
21
27
  //# sourceMappingURL=PowerSyncContext.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"PowerSyncContext.js","sourceRoot":"","sources":["../../src/hooks/PowerSyncContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC,aAAa,CAAmC,IAAI,CAAC,CAAC;AAC5F;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAC"}
1
+ {"version":3,"file":"PowerSyncContext.js","sourceRoot":"","sources":["../../src/hooks/PowerSyncContext.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,MAAM,CAAC,MAAM,gBAAgB,GAAG,KAAK,CAAC,aAAa,CAAiC,IAAI,CAAC,CAAC;AAC1F;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,YAAY;IAC1B,MAAM,EAAE,GAAG,kBAAkB,EAAE,CAAC;IAChC,IAAI,EAAE,IAAI,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;IAC7D,OAAO,EAAE,CAAC;AACZ,CAAC;AAED,MAAM,CAAC,MAAM,kBAAkB,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAC"}
@@ -1,4 +1,4 @@
1
- import { AbstractPowerSyncDatabase, SyncStreamStatus, SyncStreamSubscribeOptions } from '@powersync/common';
1
+ import { SyncStreamStatus, SyncStreamSubscribeOptions } from '@powersync/common';
2
2
  import { QuerySyncStreamOptions } from './watched/watch-types.js';
3
3
  /**
4
4
  * A sync stream to subscribe to in {@link useSyncStream}.
@@ -30,8 +30,9 @@ export declare function useSyncStream(options: UseSyncStreamOptions): SyncStream
30
30
  * React component calling this function. When it unmounts, or when the streams array contents
31
31
  * change, all previous subscriptions are unsubscribed before new ones are created.
32
32
  */
33
- export declare function useSyncStreams(streamOptions: UseSyncStreamOptions[]): SyncStreamStatus[];
33
+ export declare function useSyncStreams(streamOptions: UseSyncStreamOptions[]): (SyncStreamStatus | null)[];
34
34
  /**
35
35
  * Returns `true` once all streams in the array have synced at least once.
36
36
  */
37
- export declare function useAllSyncStreamsHaveSynced(db: AbstractPowerSyncDatabase, streams: QuerySyncStreamOptions[] | undefined): boolean;
37
+ export declare function useAllSyncStreamsHaveSynced(_db: unknown, // TODO (breaking): Remove
38
+ streams: QuerySyncStreamOptions[] | undefined): boolean;
@@ -1,6 +1,6 @@
1
1
  import { useEffect, useMemo } from 'react';
2
- import { usePowerSync } from './PowerSyncContext.js';
3
- import { useStatus } from './useStatus.js';
2
+ import { usePowerSyncOrNull } from './PowerSyncContext.js';
3
+ import { useStatusOrNull } from './useStatus.js';
4
4
  /**
5
5
  * Creates a PowerSync stream subscription. The subscription is kept alive as long as the React component calling this
6
6
  * function. When it unmounts, {@link SyncStreamSubscription.unsubscribe} is called
@@ -18,20 +18,20 @@ export function useSyncStream(options) {
18
18
  * change, all previous subscriptions are unsubscribed before new ones are created.
19
19
  */
20
20
  export function useSyncStreams(streamOptions) {
21
- const db = usePowerSync();
22
- const status = useStatus();
21
+ const db = usePowerSyncOrNull();
22
+ const status = useStatusOrNull();
23
23
  const stringifiedOptions = useMemo(() => JSON.stringify(streamOptions), [streamOptions]);
24
24
  const syncStreams = useMemo(() => streamOptions.map((options) => {
25
25
  return {
26
- stream: db.syncStream(options.name, options.parameters ?? undefined),
26
+ stream: db?.syncStream(options.name, options.parameters ?? undefined),
27
27
  options
28
28
  };
29
- }), [stringifiedOptions]);
29
+ }), [db, stringifiedOptions]);
30
30
  useEffect(() => {
31
31
  let active = true;
32
32
  const resolvedSubs = [];
33
33
  for (const entry of syncStreams) {
34
- entry.stream.subscribe(entry.options).then((sub) => {
34
+ entry.stream?.subscribe(entry.options).then((sub) => {
35
35
  if (active) {
36
36
  resolvedSubs.push(sub);
37
37
  }
@@ -47,13 +47,14 @@ export function useSyncStreams(streamOptions) {
47
47
  sub.unsubscribe();
48
48
  }
49
49
  };
50
- }, [stringifiedOptions]);
51
- return useMemo(() => syncStreams.map((entry) => status.forStream(entry.stream) ?? null), [status, stringifiedOptions]);
50
+ }, [db, stringifiedOptions]);
51
+ return useMemo(() => syncStreams.map((entry) => (entry.stream && status?.forStream(entry.stream)) ?? null), [status, syncStreams]);
52
52
  }
53
53
  /**
54
54
  * Returns `true` once all streams in the array have synced at least once.
55
55
  */
56
- export function useAllSyncStreamsHaveSynced(db, streams) {
56
+ export function useAllSyncStreamsHaveSynced(_db, // TODO (breaking): Remove
57
+ streams) {
57
58
  const statuses = useSyncStreams(streams ?? []);
58
59
  if (!streams)
59
60
  return true;
@@ -1 +1 @@
1
- {"version":3,"file":"streams.js","sourceRoot":"","sources":["../../src/hooks/streams.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,OAAO,EAAY,MAAM,OAAO,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAQrD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAoB3C;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,OAA6B;IACzD,OAAO,cAAc,CAAC,CAAC,OAAO,CAAC,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K,CAAC,MAAM,IAAI,MAAM,EAAE,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,IAAI,CAAC,EAC3F,CAAC,MAAM,EAAE,WAAW,CAAC,CACtB,CAAC;AACJ,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,2BAA2B,CACzC,GAAY,EAAE,0BAA0B;AACxC,OAA6C;IAE7C,MAAM,QAAQ,GAAG,cAAc,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;IAE/C,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IAE1B,OAAO,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACjC,IAAI,CAAC,MAAM,CAAC,aAAa;YAAE,OAAO,IAAI,CAAC;QACvC,OAAO,QAAQ,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,SAAS,KAAK,IAAI,CAAC;IACvD,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,46 @@
1
+ import { CommonPowerSyncDatabase } from '@powersync/common';
2
+ import { QueryConfig, Result } from '../watched/QueryRunner.js';
3
+ /**
4
+ * How long a query checked out by a render stays alive after it has loaded, if no component subscribes to it.
5
+ *
6
+ * React may take a while to commit a component after its suspending promise resolves (at least 300ms), so this should
7
+ * be generous.
8
+ */
9
+ export declare const TEMPORARY_HOLD_MS = 5000;
10
+ /**
11
+ * Shares {@link QueryRunner}s between suspending hooks.
12
+ *
13
+ * Components that suspend before their first commit lose all their state, so the runner for a query can't be stored
14
+ * in the component. Instead, rendering checks out the entry for a query from this cache. Checking out an entry places a
15
+ * temporary hold on it, which runs the query and keeps it alive until a component has committed and subscribed to it
16
+ * (or until the hold expires, e.g. because the render was discarded).
17
+ *
18
+ * An entry is alive exactly while it is held or has subscribers, and the cache maps each query to at most one entry.
19
+ * Hooks never reference entries directly, they use a {@link SuspenseQuery} handle that looks up the current entry for
20
+ * its query (creating it if necessary) and then sticks to that entry while it's alive.
21
+ *
22
+ * Watched queries are shared between all components using them. Queries that only run once are shared only until a
23
+ * component commits with their results: We want a suspending hook to obtain the same query when its render is retried,
24
+ * but components that have committed must be able to refresh independently, and components mounting later shouldn't
25
+ * see stale results. So the first component committing with a one-shot entry claims it, which evicts it from the cache.
26
+ * Other components that rendered with the same entry (e.g. siblings in the same suspense boundary) continue with their
27
+ * own runner, seeded with the loaded result.
28
+ */
29
+ declare class SuspenseQueryCache {
30
+ private readonly entries;
31
+ /**
32
+ * Returns a handle for the given query. Creating handles has no side effects.
33
+ */
34
+ query<RowType>(key: string, config: QueryConfig<RowType>): {
35
+ markUsed: () => void;
36
+ subscribe: (onChange: () => void) => (() => void);
37
+ getSnapshot: () => Result<RowType>;
38
+ waitForLoaded: () => Promise<void>;
39
+ };
40
+ /**
41
+ * Returns the entry for the given query after placing a temporary hold on it, creating it if necessary.
42
+ */
43
+ private checkOut;
44
+ }
45
+ export declare function getSuspenseQueryCache(db: CommonPowerSyncDatabase): SuspenseQueryCache;
46
+ export {};
@@ -0,0 +1,231 @@
1
+ import { QueryRunner } from '../watched/QueryRunner.js';
2
+ /**
3
+ * How long a query checked out by a render stays alive after it has loaded, if no component subscribes to it.
4
+ *
5
+ * React may take a while to commit a component after its suspending promise resolves (at least 300ms), so this should
6
+ * be generous.
7
+ */
8
+ export const TEMPORARY_HOLD_MS = 5_000;
9
+ /**
10
+ * Shares {@link QueryRunner}s between suspending hooks.
11
+ *
12
+ * Components that suspend before their first commit lose all their state, so the runner for a query can't be stored
13
+ * in the component. Instead, rendering checks out the entry for a query from this cache. Checking out an entry places a
14
+ * temporary hold on it, which runs the query and keeps it alive until a component has committed and subscribed to it
15
+ * (or until the hold expires, e.g. because the render was discarded).
16
+ *
17
+ * An entry is alive exactly while it is held or has subscribers, and the cache maps each query to at most one entry.
18
+ * Hooks never reference entries directly, they use a {@link SuspenseQuery} handle that looks up the current entry for
19
+ * its query (creating it if necessary) and then sticks to that entry while it's alive.
20
+ *
21
+ * Watched queries are shared between all components using them. Queries that only run once are shared only until a
22
+ * component commits with their results: We want a suspending hook to obtain the same query when its render is retried,
23
+ * but components that have committed must be able to refresh independently, and components mounting later shouldn't
24
+ * see stale results. So the first component committing with a one-shot entry claims it, which evicts it from the cache.
25
+ * Other components that rendered with the same entry (e.g. siblings in the same suspense boundary) continue with their
26
+ * own runner, seeded with the loaded result.
27
+ */
28
+ class SuspenseQueryCache {
29
+ entries = new Map();
30
+ /**
31
+ * Returns a handle for the given query. Creating handles has no side effects.
32
+ */
33
+ query(key, config) {
34
+ let entry = null;
35
+ // For one-shot queries, a runner owned by this handle after another one claimed the shared entry.
36
+ let settledOneShotFork = null;
37
+ const current = () => {
38
+ if (entry == null || entry.isRemoved) {
39
+ entry = this.entries.get(key) ?? this.checkOut(key, config);
40
+ }
41
+ return entry;
42
+ };
43
+ const handle = {
44
+ markUsed: () => {
45
+ if (settledOneShotFork != null) {
46
+ return;
47
+ }
48
+ else if (entry == null || entry.isRemoved) {
49
+ entry = this.checkOut(key, config);
50
+ }
51
+ else {
52
+ entry.ensureHeld();
53
+ }
54
+ },
55
+ subscribe: (onChange) => {
56
+ if (settledOneShotFork == null) {
57
+ const shared = current();
58
+ if (shared.claim(handle)) {
59
+ return shared.subscribe(onChange);
60
+ }
61
+ settledOneShotFork = new QueryRunner();
62
+ settledOneShotFork.configure(config, shared.getSnapshot());
63
+ }
64
+ return settledOneShotFork.subscribe(onChange);
65
+ },
66
+ getSnapshot: () => {
67
+ return (settledOneShotFork ?? current()).getSnapshot();
68
+ },
69
+ waitForLoaded: () => {
70
+ return current().loaded;
71
+ }
72
+ };
73
+ return handle;
74
+ }
75
+ /**
76
+ * Returns the entry for the given query after placing a temporary hold on it, creating it if necessary.
77
+ */
78
+ checkOut(key, config) {
79
+ let entry = this.entries.get(key);
80
+ if (entry == null) {
81
+ const created = new SuspenseQueryEntry(config, () => {
82
+ // A claimed entry may have been replaced already, don't evict its replacement.
83
+ if (this.entries.get(key) === created) {
84
+ this.entries.delete(key);
85
+ }
86
+ });
87
+ this.entries.set(key, created);
88
+ entry = created;
89
+ }
90
+ entry.ensureHeld();
91
+ return entry;
92
+ }
93
+ }
94
+ class SuspenseQueryEntry {
95
+ evict;
96
+ runner = new QueryRunner();
97
+ /**
98
+ * The number of subscribed components, not counting the temporary hold.
99
+ */
100
+ subscribers = 0;
101
+ releaseHold = null;
102
+ holdTimeout = null;
103
+ pendingLoad = null;
104
+ runOnce;
105
+ /**
106
+ * For one-shot queries, the handle of the component that has committed with this entry.
107
+ */
108
+ owner = null;
109
+ /**
110
+ * Set once this entry is neither held nor subscribed to. Its runner is idle then, and it must not be used again.
111
+ */
112
+ isRemoved = false;
113
+ constructor(config,
114
+ /**
115
+ * Evicts this entry from the cache, called once it's removed or claimed.
116
+ */
117
+ evict) {
118
+ this.evict = evict;
119
+ this.runOnce = config.runOnce;
120
+ // We call configure once here, and then never again. A changed config is represented by a fresh query entry
121
+ // (necessary to potentially re-use this across components).
122
+ this.runner.configure(config);
123
+ }
124
+ /**
125
+ * Called before a committed component subscribes through the given handle. Returns whether it may subscribe to this
126
+ * entry, or whether it needs to use its own runner instead.
127
+ *
128
+ * Watched queries can always be shared. For queries running once, the first committing component takes ownership of
129
+ * this entry, so that refreshing it doesn't affect other components and components mounting later don't get its
130
+ * (potentially stale) result.
131
+ */
132
+ claim(handle) {
133
+ if (!this.runOnce) {
134
+ return true;
135
+ }
136
+ if (this.owner == null) {
137
+ this.owner = handle;
138
+ this.evict();
139
+ }
140
+ // In StrictMode, React unsubscribes and resubscribes right away, so the owner may claim this entry again.
141
+ return this.owner === handle;
142
+ }
143
+ subscribe(onChange) {
144
+ this.subscribers++;
145
+ // Note that we don't release the temporary hold here: In StrictMode, React unsubscribes and resubscribes right
146
+ // away, which would otherwise dispose and restart the query. The hold expires on its own shortly after loading.
147
+ const unsubscribe = this.runner.subscribe(() => {
148
+ this.onRunnerChange();
149
+ onChange();
150
+ });
151
+ return () => {
152
+ unsubscribe();
153
+ this.subscribers--;
154
+ this.removeIfUnused();
155
+ };
156
+ }
157
+ getSnapshot() {
158
+ return this.runner.getSnapshot();
159
+ }
160
+ /**
161
+ * A promise to throw while the query is loading. It's stable until the query has loaded, and resolves once the
162
+ * query has a result or an error.
163
+ */
164
+ get loaded() {
165
+ if (this.isSettled) {
166
+ return Promise.resolve();
167
+ }
168
+ if (this.pendingLoad == null) {
169
+ let resolve;
170
+ const promise = new Promise((r) => (resolve = r));
171
+ this.pendingLoad = { promise, resolve };
172
+ }
173
+ return this.pendingLoad.promise;
174
+ }
175
+ /**
176
+ * Places a temporary hold on this entry for a render that checked it out, or extends the existing one.
177
+ *
178
+ * We do this even if components are subscribed already, since they might unsubscribe before the render checking
179
+ * out this entry commits (e.g. when one component unmounts while another one using the same query mounts).
180
+ */
181
+ ensureHeld() {
182
+ if (this.releaseHold == null) {
183
+ // If this is the first listener, subscribing starts running the query. The runner then only notifies its own
184
+ // listeners, which is just the hold. Otherwise, it doesn't notify anyone. So this is safe to call while rendering.
185
+ this.releaseHold = this.runner.subscribe(() => this.onRunnerChange());
186
+ }
187
+ else if (this.holdTimeout != null) {
188
+ // Restart the timer in onRunnerChange, so that the hold lasts until shortly after the latest checkout.
189
+ clearTimeout(this.holdTimeout);
190
+ this.holdTimeout = null;
191
+ }
192
+ this.onRunnerChange();
193
+ }
194
+ get isSettled() {
195
+ const snapshot = this.runner.getSnapshot();
196
+ return !snapshot.isLoading || snapshot.error != null;
197
+ }
198
+ onRunnerChange() {
199
+ if (!this.isSettled) {
200
+ return;
201
+ }
202
+ this.pendingLoad?.resolve();
203
+ this.pendingLoad = null;
204
+ if (this.releaseHold != null && this.holdTimeout == null) {
205
+ this.holdTimeout = setTimeout(() => {
206
+ this.holdTimeout = null;
207
+ this.releaseHold?.();
208
+ this.releaseHold = null;
209
+ this.removeIfUnused();
210
+ }, TEMPORARY_HOLD_MS);
211
+ }
212
+ }
213
+ removeIfUnused() {
214
+ if (this.subscribers == 0 && this.releaseHold == null) {
215
+ // The runner has disposed its work since it has no listeners left.
216
+ this.isRemoved = true;
217
+ this.evict();
218
+ }
219
+ }
220
+ }
221
+ let caches;
222
+ export function getSuspenseQueryCache(db) {
223
+ caches ??= new WeakMap();
224
+ let cache = caches.get(db);
225
+ if (cache == null) {
226
+ cache = new SuspenseQueryCache();
227
+ caches.set(db, cache);
228
+ }
229
+ return cache;
230
+ }
231
+ //# sourceMappingURL=SuspenseQueryCache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SuspenseQueryCache.js","sourceRoot":"","sources":["../../../src/hooks/suspense/SuspenseQueryCache.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,WAAW,EAAU,MAAM,2BAA2B,CAAC;AAE7E;;;;;GAKG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,KAAK,CAAC;AAEvC;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,kBAAkB;IACL,OAAO,GAAG,IAAI,GAAG,EAAmC,CAAC;IAEtE;;OAEG;IACH,KAAK,CAAU,GAAW,EAAE,MAA4B;QACtD,IAAI,KAAK,GAAuC,IAAI,CAAC;QACrD,kGAAkG;QAClG,IAAI,kBAAkB,GAAgC,IAAI,CAAC;QAC3D,MAAM,OAAO,GAAG,GAAG,EAAE;YACnB,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;gBACrC,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YAC9D,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;QAEF,MAAM,MAAM,GAAG;YACb,QAAQ,EAAE,GAAG,EAAE;gBACb,IAAI,kBAAkB,IAAI,IAAI,EAAE,CAAC;oBAC/B,OAAO;gBACT,CAAC;qBAAM,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;oBAC5C,KAAK,GAAG,IAAI,CAAC,QAAQ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AClB,KAAK,GAAG,IAAI,kBAAkB,EAAE,CAAC;QACjC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IACxB,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { CompilableQuery } from '@powersync/common';
2
- import { AdditionalOptions, DifferentialHookOptions } from '../watched/watch-types.js';
2
+ import { DifferentialSuspenseQueryOptions, SuspenseQueryOptions } from '../watched/watch-types.js';
3
3
  import { ReadonlySuspenseQueryResult, SuspenseQueryResult } from './SuspenseQueryResult.js';
4
4
  /**
5
5
  * A hook to access the results of a watched query that suspends until the initial result has loaded.
@@ -49,5 +49,5 @@ import { ReadonlySuspenseQueryResult, SuspenseQueryResult } from './SuspenseQuer
49
49
  * );
50
50
  * }
51
51
  */
52
- export declare function useSuspenseQuery<RowType = any>(query: string | CompilableQuery<RowType>, parameters?: any[], options?: AdditionalOptions): SuspenseQueryResult<RowType>;
53
- export declare function useSuspenseQuery<RowType = any>(query: string | CompilableQuery<RowType>, paramerers?: any[], options?: DifferentialHookOptions<RowType>): ReadonlySuspenseQueryResult<RowType>;
52
+ export declare function useSuspenseQuery<RowType = any>(query: string | CompilableQuery<RowType>, parameters?: any[], options?: SuspenseQueryOptions): SuspenseQueryResult<RowType>;
53
+ export declare function useSuspenseQuery<RowType = any>(query: string | CompilableQuery<RowType>, parameters?: any[], options?: DifferentialSuspenseQueryOptions<RowType>): ReadonlySuspenseQueryResult<RowType>;
@@ -1,11 +1,32 @@
1
- import { useSingleSuspenseQuery } from './useSingleSuspenseQuery.js';
2
- import { useWatchedSuspenseQuery } from './useWatchedSuspenseQuery.js';
1
+ import { useContext, useMemo, useSyncExternalStore } from 'react';
2
+ import { PowerSyncContext } from '../PowerSyncContext.js';
3
+ import { configError, configKey, resolveConfig } from '../watched/QueryRunner.js';
4
+ import { constructCompatibleQuery } from '../watched/watch-utils.js';
5
+ import { getSuspenseQueryCache } from './SuspenseQueryCache.js';
3
6
  export function useSuspenseQuery(query, parameters = [], options = {}) {
4
- switch (options?.runQueryOnce) {
5
- case true:
6
- return useSingleSuspenseQuery(query, parameters, options);
7
- default:
8
- return useWatchedSuspenseQuery(query, parameters, options);
7
+ const powerSync = useContext(PowerSyncContext);
8
+ const parsedQuery = constructCompatibleQuery(query, parameters);
9
+ const config = resolveConfig(powerSync, parsedQuery, options,
10
+ // We currently don't support sync streams here (useAllStreamsHaveSynced relies on useEffect, which don't fire in
11
+ // suspended components).
12
+ true);
13
+ if (config.kind != 'query') {
14
+ // Missing database or a query that failed to compile, report.
15
+ throw configError(config);
9
16
  }
17
+ // A component that suspends before its first commit loses all its state, so the runner for this query is stored in
18
+ // a cache shared between components instead of in a ref.
19
+ const cache = getSuspenseQueryCache(config.db);
20
+ const key = configKey(config);
21
+ const suspenseQuery = useMemo(() => cache.query(key, config), [cache, key]);
22
+ suspenseQuery.markUsed();
23
+ const result = useSyncExternalStore(suspenseQuery.subscribe, suspenseQuery.getSnapshot, suspenseQuery.getSnapshot);
24
+ if (result.error != null) {
25
+ throw result.error;
26
+ }
27
+ else if (result.isLoading) {
28
+ throw suspenseQuery.waitForLoaded();
29
+ }
30
+ return { data: result.data, refresh: result.refresh };
10
31
  }
11
32
  //# sourceMappingURL=useSuspenseQuery.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useSuspenseQuery.js","sourceRoot":"","sources":["../../../src/hooks/suspense/useSuspenseQuery.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AA4DvE,MAAM,UAAU,gBAAgB,CAC9B,KAAwC,EACxC,aAAoB,EAAE,EACtB,UAAgE,EAAE;IAElE,QAAQ,OAAO,EAAE,YAAY,EAAE,CAAC;QAC9B,KAAK,IAAI;YACP,OAAO,sBAAsB,CAAU,KAAK,EAAE,UAAU,EAAE,OAAO,CAAC,CAAC;QACr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AAC,CAAC,CAAC;IAC5E,aAAa,CAAC,QAAQ,EAAE,CAAC;IACzB,MAAM,MAAM,GAAG,oBAAoB,CAAC,aAAa,CAAC,SAAS,EAAE,aAAa,CAAC,WAAW,EAAE,aAAa,CAAC,WAAW,CAAC,CAAC;IAEnH,IAAI,MAAM,CAAC,KAAK,IAAI,IAAI,EAAE,CAAC;QACzB,MAAM,MAAM,CAAC,KAAK,CAAC;IACrB,CAAC;SAAM,IAAI,MAAM,CAAC,SAAS,EAAE,CAAC;QAC5B,MAAM,aAAa,CAAC,aAAa,EAAE,CAAC;IACtC,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAiB,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,CAAC;AACrE,CAAC"}
@@ -1,5 +1,4 @@
1
- import React from 'react';
2
- import { createSuspendingPromise, useTemporaryHold } from './suspense-utils.js';
1
+ import { useCallback, useSyncExternalStore } from 'react';
3
2
  /**
4
3
  * A hook to access and subscribe to the results of an existing {@link WatchedQuery}.
5
4
  * @example
@@ -22,31 +21,68 @@ import { createSuspendingPromise, useTemporaryHold } from './suspense-utils.js';
22
21
  * }
23
22
  */
24
23
  export const useWatchedQuerySuspenseSubscription = (query) => {
25
- useTemporaryHold(query);
26
- // Force update state function
27
- const [, setUpdateCounter] = React.useState(0);
28
- React.useEffect(() => {
29
- // This runs when the component came out of suspense
30
- // This add a permanent hold since a listener has been added to the query
31
- const dispose = query.registerListener({
32
- onStateChange() {
33
- // Trigger rerender
34
- setUpdateCounter((prev) => prev + 1);
35
- }
36
- });
37
- return dispose;
38
- }, []);
39
- if (query.state.error != null) {
40
- // Report errors - this is caught by an error boundary
41
- throw query.state.error;
24
+ const subscribe = useCallback((onChange) => query.registerListener({ onStateChange: onChange }), [query]);
25
+ const getSnapshot = useCallback(() => snapshotState(query), [query]);
26
+ const state = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
27
+ if (state.error != null) {
28
+ throw state.error;
42
29
  }
43
- else if (!query.state.isLoading) {
44
- // Happy path data return
45
- return query.state;
30
+ else if (!state.isLoading) {
31
+ return state;
46
32
  }
47
33
  else {
48
- // Notify suspense is required
49
- throw createSuspendingPromise(query);
34
+ // Suspend until the query has results or an error.
35
+ throw suspendUntilDataOrError(query);
50
36
  }
51
37
  };
38
+ let suspendingPromises;
39
+ let stateSnapshots;
40
+ /**
41
+ * A promise that resolves once the query has loaded, cached to be suitable for hooks.
42
+ */
43
+ function suspendUntilDataOrError(query) {
44
+ const promises = (suspendingPromises ??= new WeakMap());
45
+ const existing = promises.get(query);
46
+ if (existing) {
47
+ return existing;
48
+ }
49
+ const promise = new Promise((resolve) => {
50
+ // The listener here will dispose itself once the loading is done.
51
+ // This decreases the number of listeners on the query even if the component is unmounted.
52
+ const dispose = query.registerListener({
53
+ onStateChange: (state) => {
54
+ // Returns to the hook if loading is completed or if loading resulted in an error
55
+ if (!state.isLoading || state.error) {
56
+ promises.delete(query);
57
+ resolve();
58
+ dispose();
59
+ }
60
+ }
61
+ });
62
+ });
63
+ promises.set(query, promise);
64
+ return promise;
65
+ }
66
+ /**
67
+ * Returns a stable copy of the query's state.
68
+ *
69
+ * Watched queries update their `state` object in place, so it can't be used as a snapshot for `useSyncExternalStore`
70
+ * directly.
71
+ */
72
+ function snapshotState(query) {
73
+ const state = query.state;
74
+ const snapshots = (stateSnapshots ??= new WeakMap());
75
+ const cached = snapshots.get(query);
76
+ if (cached != null &&
77
+ cached.data === state.data &&
78
+ cached.isLoading === state.isLoading &&
79
+ cached.isFetching === state.isFetching &&
80
+ cached.error === state.error &&
81
+ cached.lastUpdated === state.lastUpdated) {
82
+ return cached;
83
+ }
84
+ const snapshot = { ...state };
85
+ snapshots.set(query, snapshot);
86
+ return snapshot;
87
+ }
52
88
  //# sourceMappingURL=useWatchedQuerySuspenseSubscription.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useWatchedQuerySuspenseSubscription.js","sourceRoot":"","sources":["../../../src/hooks/suspense/useWatchedQuerySuspenseSubscription.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEhF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG,CAIjD,KAAY,EACI,EAAE;IAClB,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAExB,8BAA8B;IAC9B,MAAM,CAAC,EAAE,gBAAgB,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;IAE/C,KAAK,CAAC,SAAS,CAAC,GAAG,EAAE;QACnB,oDAAoD;QACpD,yEAAyE;QACzE,MAAM,OAAO,GAAG,KAAK,CAAC,gBAAgB,CAAC;YACrC,aAAa;gBACX,mBAAmB;gBACnB,gBAAgB,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;YACvC,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC;IACjB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,IAAI,KAAK,CAAC,KAAK,CAAC,KAAK,IAAI,IAAI,EAAE,CAAC;QAC9B,sDAAsD;QACtD,MAAM,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC;IAC1B,CAAC;SAAM,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,SAAS,EAAE,CAAC;QAClC,yBAAyB;QACzB,OAAO,KAAK,CAAC,KAAK,CAAC;IACrB,CAAC;SAAM,CAAC;QACN,8BAA8B;QAC9B,MAAM,uBAAuB,CAAC,KAAK,CAAC,CAAC;IACvC,CAAC;AACH,CAAC,CAAC"}
1
+ {"version":3,"file":"useWatchedQuerySuspenseSubscription.js","sourceRoot":"","sources":["../../../src/hooks/suspense/useWatchedQuerySuspenseSubscription.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,oBAAoB,EAAE,MAAM,OAAO,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C,KAAK,EAAE,EAAE;gBACvB,iFAAiF;gBACjF,IAAI,CAAC,KAAK,CAAC,SAAS,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;oBACpC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;oBACvB,OAAO,EAAE,CAAC;oBACV,OAAO,EAAE,CAAC;gBACZ,CAAC;YACH,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IACH,QAAQ,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IAC7B,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;GAKG;AACH,SAAS,aAAa,CAAO,KAAyB;IACpD,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,CAAC;IAC1B,MAAM,SAAS,GAAG,CAAC,cAAc,KAAK,IAAI,OAAO,EAAE,CAAC,CAAC;IACrD,MAAM,MAAM,GAAG,SAAS,CAAC,GAAG,CAAC,KAAK,CAAwC,CAAC;IAC3E,IACE,MAAM,IAAI,IAAI;QACd,MAAM,CAAC,IAAI,KAAK,KAAK,CAAC,IAAI;QAC1B,MAAM,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS;QACpC,MAAM,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU;QACtC,MAAM,CAAC,KAAK,KAAK,KAAK,CAAC,KAAK;QAC5B,MAAM,CAAC,WAAW,KAAK,KAAK,CAAC,WAAW,EACxC,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IAC9B,SAAS,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IAC/B,OAAO,QAAQ,CAAC;AAClB,CAAC"}
@@ -1,3 +1,4 @@
1
+ import { SyncStatus } from '@powersync/common';
1
2
  /**
2
3
  * Custom hook that provides access to the current status of PowerSync.
3
4
  * @returns The PowerSync Database status.
@@ -12,4 +13,9 @@
12
13
  * </div>
13
14
  * };
14
15
  */
15
- export declare function useStatus(): import("@powersync/common").SyncStatus;
16
+ export declare function useStatus(): SyncStatus;
17
+ /**
18
+ * @internal
19
+ */
20
+ export declare function useStatusOrNull(allowNull?: boolean): SyncStatus | null;
21
+ export declare function useStatusOrNull(allowNull: false): SyncStatus;