@powersync/react 0.0.0-dev-20260630144038 → 0.0.0-dev-20261015114518

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 -39
  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 +12 -10
  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 -40
  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
@@ -1,13 +0,0 @@
1
- import { DifferentialHookOptions, QueryResult, ReadonlyQueryResult } from './watch-types.js';
2
- import { InternalHookOptions } from './watch-utils.js';
3
- /**
4
- * @internal This is not exported from the index.ts
5
- *
6
- * When an incremental query is used the return type is readonly. This is required
7
- * since the implementation requires a stable ref.
8
- * For legacy compatibility we allow mutating when a standard query is used. Mutations should
9
- * not affect the internal implementation in this case.
10
- */
11
- export declare const useWatchedQuery: <RowType = unknown>(options: InternalHookOptions<RowType[]> & {
12
- options: DifferentialHookOptions<RowType>;
13
- }) => QueryResult<RowType> | ReadonlyQueryResult<RowType>;
@@ -1,81 +0,0 @@
1
- import React from 'react';
2
- import { useNullableWatchedQuerySubscription } from './useWatchedQuerySubscription.js';
3
- /**
4
- * @internal This is not exported from the index.ts
5
- *
6
- * When an incremental query is used the return type is readonly. This is required
7
- * since the implementation requires a stable ref.
8
- * For legacy compatibility we allow mutating when a standard query is used. Mutations should
9
- * not affect the internal implementation in this case.
10
- */
11
- export const useWatchedQuery = (options) => {
12
- const { query, powerSync, queryChanged, options: hookOptions, active } = options;
13
- function createWatchedQuery() {
14
- if (!active) {
15
- return null;
16
- }
17
- const watch = hookOptions.rowComparator
18
- ? powerSync.customQuery(query).differentialWatch({
19
- rowComparator: hookOptions.rowComparator,
20
- reportFetching: hookOptions.reportFetching,
21
- throttleMs: hookOptions.throttleMs
22
- })
23
- : powerSync.customQuery(query).watch({
24
- reportFetching: hookOptions.reportFetching,
25
- throttleMs: hookOptions.throttleMs
26
- });
27
- return watch;
28
- }
29
- const [watchedQuery, setWatchedQuery] = React.useState(createWatchedQuery);
30
- const disposePendingUpdateListener = React.useRef(null);
31
- React.useEffect(() => {
32
- watchedQuery?.close();
33
- const newQuery = createWatchedQuery();
34
- setWatchedQuery(newQuery);
35
- return () => {
36
- disposePendingUpdateListener.current?.();
37
- newQuery?.close();
38
- };
39
- }, [powerSync, active]);
40
- /**
41
- * Indicates that the query will be re-fetched due to a change in the query.
42
- * We execute this in-line (not using an effect) since effects are delayed till after the hook returns.
43
- * The `queryChanged` value should only be true for a single render.
44
- * The `updateSettings` method is asynchronous, thus it will update the state asynchronously.
45
- * In the React hooks we'd like to report that we are fetching the data for an updated query
46
- * as soon as the query has been updated. This prevents a result flow where e.g. the hook:
47
- * - already returned a result: isLoading, isFetching are both false
48
- * - the query is updated, but the state is still isFetching=false from the previous state
49
- * We override the isFetching status while the `updateSettings` method is running (if we report `isFetching`),
50
- * we override this value just until the `updateSettings` method itself will update the `isFetching` status.
51
- * We achieve this by registering a `settingsWillUpdate` listener on the `WatchedQuery`. This will fire
52
- * just before the `isFetching` status is updated.
53
- */
54
- if (queryChanged) {
55
- // Keep track of this pending operation
56
- watchedQuery?.updateSettings({
57
- query,
58
- throttleMs: hookOptions.throttleMs,
59
- reportFetching: hookOptions.reportFetching
60
- });
61
- // This could have been called multiple times, clear any old listeners.
62
- disposePendingUpdateListener.current?.();
63
- disposePendingUpdateListener.current = watchedQuery?.registerListener({
64
- settingsWillUpdate: () => {
65
- // We'll use the fact that we have a listener at all as an indication
66
- disposePendingUpdateListener.current?.();
67
- disposePendingUpdateListener.current = null;
68
- }
69
- });
70
- }
71
- const shouldReportCurrentlyFetching = (hookOptions.reportFetching ?? true) && !!disposePendingUpdateListener.current;
72
- const result = useNullableWatchedQuerySubscription(watchedQuery);
73
- // Result is only undefined when there is no data available yet, defaults are defined accordingly
74
- return {
75
- data: result?.data ?? [],
76
- isLoading: result?.isLoading ?? true,
77
- error: result?.error,
78
- isFetching: result?.isFetching || shouldReportCurrentlyFetching
79
- };
80
- };
81
- //# sourceMappingURL=useWatchedQuery.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"useWatchedQuery.js","sourceRoot":"","sources":["../../../src/hooks/watched/useWatchedQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kCAAkC,CAAC;AAIvF;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAC7B,OAAuF,EAClC,EAAE;IACvD,MAAM,EAAE,KAAK,EAAE,SAAS,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAEjF,SAAS,kBAAkB;QACzB,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACd,CAAC;QAED,MAAM,KAAK,GAAG,WAAW,CAAC,aAAa;YACrC,CAAC,CAAC,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,iBAAiB,CAAC;gBAC7C,aAAa,EAAE,WAAW,CAAC,aAAa;gBACxC,cAAc,EAAE,WAAW,CAAC,cAAc;gBAC1C,UAAU,EAAE,WAAW,CAAC,UAAU;aACnC,CAAC;YACJ,CAAC,CAAC,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC;gBACjC,cAAc,EAAE,WAAW,CAAC,cAAc;gBAC1C,UAAU,EAAE,WAAW,CAAC,UAAU;aACnC,CAAC,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,CAAC,YAAY,EAAE,eAAe,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;IAC3E,MAAM,4BAA4B,GAAG,KAAK,CAAC,MAAM,CAAoB,IAAI,CAAC,CAAC;IAE3E,KAAK,CAAC,SAAS,CAAC,GAAG,EAAE;QACnB,YAAY,EAAE,KAAK,EAAE,CAAC;QACtB,MAAM,QAAQ,GAAG,kBAAkB,EAAE,CAAC;QACtC,eAAe,CAAC,QAAQ,CAAC,CAAC;QAE1B,OAAO,GAAG,EAAE;YACV,4BAA4B,CAAC,OAAO,EAAE,EAAE,CAAC;YACzC,QAAQ,EAAE,KAAK,EAAE,CAAC;QACpB,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;IAExB;;;;;;;;;;;;;OAaG;IACH,IAAI,YAAY,EAAE,CAAC;QACjB,uCAAuC;QACvC,YAAY,EAAE,cAAc,CAAC;YAC3B,KAAK;YACL,UAAU,EAAE,WAAW,CAAC,UAAU;YAClC,cAAc,EAAE,WAAW,CAAC,cAAc;SAC3C,CAAC,CAAC;QACH,uEAAuE;QACvE,4BAA4B,CAAC,OAAO,EAAE,EAAE,CAAC;QACzC,4BAA4B,CAAC,OAAO,GAAG,YAAY,EAAE,gBAAgB,CAAC;YACpE,kBAAkB,EAAE,GAAG,EAAE;gBACvB,qEAAqE;gBACrE,4BAA4B,CAAC,OAAO,EAAE,EAAE,CAAC;gBACzC,4BAA4B,CAAC,OAAO,GAAG,IAAI,CAAC;YAC9C,CAAC;SACF,CAAC,CAAC;IACL,CAAC;IAED,MAAM,6BAA6B,GAAG,CAAC,WAAW,CAAC,cAAc,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,4BAA4B,CAAC,OAAO,CAAC;IACrH,MAAM,MAAM,GAAG,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAEjE,iGAAiG;IACjG,OAAO;QACL,IAAI,EAAE,MAAM,EAAE,IAAI,IAAI,EAAE;QACxB,SAAS,EAAE,MAAM,EAAE,SAAS,IAAI,IAAI;QACpC,KAAK,EAAE,MAAM,EAAE,KAAK;QACpB,UAAU,EAAE,MAAM,EAAE,UAAU,IAAI,6BAA6B;KAChE,CAAC;AACJ,CAAC,CAAC"}
package/src/QueryStore.ts DELETED
@@ -1,81 +0,0 @@
1
- import {
2
- AbstractPowerSyncDatabase,
3
- WatchCompatibleQuery,
4
- WatchedQuery,
5
- WatchedQueryListenerEvent
6
- } from '@powersync/common';
7
- import { DifferentialHookOptions } from './hooks/watched/watch-types.js';
8
-
9
- export function generateQueryKey(
10
- sqlStatement: string,
11
- parameters: ReadonlyArray<unknown>,
12
- options: DifferentialHookOptions<unknown>
13
- ): string {
14
- return `${sqlStatement} -- ${JSON.stringify(parameters)} -- ${JSON.stringify(options)}`;
15
- }
16
-
17
- export class QueryStore {
18
- cache = new Map<string, WatchedQuery<unknown>>();
19
-
20
- constructor(private db: AbstractPowerSyncDatabase) {}
21
-
22
- getQuery<RowType>(key: string, query: WatchCompatibleQuery<RowType[]>, options: DifferentialHookOptions<RowType>) {
23
- if (this.cache.has(key)) {
24
- return this.cache.get(key) as WatchedQuery<RowType[]>;
25
- }
26
-
27
- const watch = options.rowComparator
28
- ? this.db.customQuery(query).differentialWatch({
29
- rowComparator: options.rowComparator,
30
- reportFetching: options.reportFetching,
31
- throttleMs: options.throttleMs
32
- })
33
- : this.db.customQuery(query).watch({
34
- reportFetching: options.reportFetching,
35
- throttleMs: options.throttleMs
36
- });
37
-
38
- this.cache.set(key, watch);
39
-
40
- const disposer = watch.registerListener({
41
- closed: () => {
42
- this.cache.delete(key);
43
- disposer?.();
44
- }
45
- });
46
-
47
- watch.listenerMeta.registerListener({
48
- listenersChanged: (counts) => {
49
- // Dispose this query if there are no subscribers present
50
- // We don't use the total here since we don't want to consider `onclose` listeners
51
- const relevantCounts = [
52
- WatchedQueryListenerEvent.ON_DATA,
53
- WatchedQueryListenerEvent.ON_STATE_CHANGE,
54
- WatchedQueryListenerEvent.ON_ERROR
55
- ].reduce((sum, event) => {
56
- return sum + (counts[event] || 0);
57
- }, 0);
58
-
59
- if (relevantCounts == 0) {
60
- watch.close();
61
- this.cache.delete(key);
62
- }
63
- }
64
- });
65
-
66
- return watch;
67
- }
68
- }
69
-
70
- let queryStores: WeakMap<AbstractPowerSyncDatabase, QueryStore> | undefined = undefined;
71
-
72
- export function getQueryStore(db: AbstractPowerSyncDatabase): QueryStore {
73
- queryStores ||= new WeakMap();
74
- const existing = queryStores.get(db);
75
- if (existing) {
76
- return existing;
77
- }
78
- const store = new QueryStore(db);
79
- queryStores.set(db, store);
80
- return store;
81
- }
@@ -1,86 +0,0 @@
1
- import { WatchedQuery } from '@powersync/common';
2
- import React from 'react';
3
-
4
- /**
5
- * The store will dispose this query if it has no subscribers attached to it.
6
- * The suspense promise adds a subscriber to the query, but the promise could resolve
7
- * before this component is committed. The promise will release it's listener once the query is no longer loading.
8
- * This temporary hold is used to ensure that the query is not disposed in the interim.
9
- * Creates a subscription for state change which creates a temporary hold on the query
10
- */
11
- export const useTemporaryHold = (watchedQuery?: WatchedQuery<unknown>) => {
12
- const releaseTemporaryHold = React.useRef<() => void | undefined>(undefined);
13
- const addedHoldTo = React.useRef<WatchedQuery<unknown> | undefined>(undefined);
14
-
15
- if (addedHoldTo.current !== watchedQuery) {
16
- // The query changed, we no longer need the previous hold if present
17
- releaseTemporaryHold.current?.();
18
- releaseTemporaryHold.current = undefined;
19
- addedHoldTo.current = watchedQuery;
20
-
21
- if (!watchedQuery || !watchedQuery.state.isLoading) {
22
- // No query to hold or no reason to hold, return
23
- return;
24
- }
25
-
26
- // Create a hold by subscribing
27
- const disposeSubscription = watchedQuery.registerListener({
28
- onStateChange: (state) => {}
29
- });
30
-
31
- let timeout: ReturnType<typeof setTimeout>;
32
-
33
- const disposeClosedListener = watchedQuery.registerListener({
34
- closed: () => {
35
- if (timeout) {
36
- clearTimeout(timeout);
37
- }
38
- disposeClosedListener();
39
- }
40
- });
41
-
42
- const releaseHold = () => {
43
- disposeSubscription();
44
- disposeClosedListener();
45
- };
46
- releaseTemporaryHold.current = releaseHold;
47
-
48
- const timeoutPollMs = 5_000;
49
-
50
- const checkHold = () => {
51
- if (watchedQuery.closed || !watchedQuery.state.isLoading || watchedQuery.state.error) {
52
- // No need to keep a temporary hold on this query
53
- releaseHold();
54
- } else {
55
- // Need to keep the hold, check again after timeout
56
- setTimeout(checkHold, timeoutPollMs);
57
- }
58
- };
59
-
60
- // Set a timeout to conditionally remove the temporary hold
61
- setTimeout(checkHold, timeoutPollMs);
62
- }
63
- };
64
-
65
- /**
66
- * React suspense relies on a promise that resolves once the initial data has loaded.
67
- * This creates a promise which registers a listener on the watched query.
68
- * Registering a listener on the watched query will ensure that the query is not disposed
69
- * while the component is suspended.
70
- */
71
- export const createSuspendingPromise = (query: WatchedQuery<unknown>) => {
72
- return new Promise<void>((resolve) => {
73
- // The listener here will dispose itself once the loading is done
74
- // This decreases the number of listeners on the query
75
- // even if the component is unmounted
76
- const dispose = query.registerListener({
77
- onStateChange: (state) => {
78
- // Returns to the hook if loading is completed or if loading resulted in an error
79
- if (!state.isLoading || state.error) {
80
- resolve();
81
- dispose();
82
- }
83
- }
84
- });
85
- });
86
- };
@@ -1,81 +0,0 @@
1
- import { CompilableQuery, WatchedQuery } from '@powersync/common';
2
- import React from 'react';
3
- import { generateQueryKey, getQueryStore } from '../../QueryStore.js';
4
- import { usePowerSync } from '../PowerSyncContext.js';
5
- import { AdditionalOptions } from '../watched/watch-types.js';
6
- import { constructCompatibleQuery } from '../watched/watch-utils.js';
7
- import { createSuspendingPromise, useTemporaryHold } from './suspense-utils.js';
8
- import { SuspenseQueryResult } from './SuspenseQueryResult.js';
9
-
10
- /**
11
- * Use a query which is not watched, but suspends until the initial result has loaded.
12
- * Internally this uses a WatchedQuery during suspense for state management. The watched
13
- * query is potentially disposed, if there are no subscribers attached to it, after the initial load.
14
- * The query can be refreshed by calling the `refresh` function after initial load.
15
- */
16
- export const useSingleSuspenseQuery = <T = any>(
17
- query: string | CompilableQuery<T>,
18
- parameters: any[] = [],
19
- options: AdditionalOptions = {}
20
- ): SuspenseQueryResult<T> => {
21
- const powerSync = usePowerSync();
22
- if (!powerSync) {
23
- throw new Error('PowerSync not configured.');
24
- }
25
-
26
- // Manually track data for single queries
27
- const [data, setData] = React.useState<T[] | null>(null);
28
- const [error, setError] = React.useState<Error | null>(null);
29
-
30
- // Note, we don't need to check if the query changed since we fetch the WatchedQuery
31
- // from the store given these query params
32
- const { parsedQuery } = constructCompatibleQuery(query, parameters, options);
33
- const { sql: parsedSql, parameters: parsedParameters } = parsedQuery.compile();
34
-
35
- const key = generateQueryKey(parsedSql, parsedParameters, options);
36
- const store = getQueryStore(powerSync);
37
-
38
- // Only use a temporary watched query if we don't have data yet.
39
- const watchedQuery = data ? null : (store.getQuery(key, parsedQuery, options) as WatchedQuery<T[]>);
40
- useTemporaryHold(watchedQuery);
41
- React.useEffect(() => {
42
- // Set the initial yielded data
43
- // it should be available once we commit the component
44
- if (watchedQuery?.state.error) {
45
- setError(watchedQuery.state.error);
46
- } else if (watchedQuery?.state.isLoading === false) {
47
- setData(watchedQuery.state.data);
48
- setError(null);
49
- }
50
- }, []);
51
-
52
- if (error != null) {
53
- // Report errors - this is caught by an error boundary
54
- throw error;
55
- } else if (data || watchedQuery?.state.isLoading === false) {
56
- // Happy path data return
57
- return {
58
- data: data ?? watchedQuery?.state.data ?? [],
59
- refresh: async (signal) => {
60
- try {
61
- const compiledQuery = parsedQuery.compile();
62
- const result = await parsedQuery.execute({
63
- sql: compiledQuery.sql,
64
- parameters: [...compiledQuery.parameters],
65
- db: powerSync
66
- });
67
- if (signal.aborted) {
68
- return; // Abort if the signal is already aborted
69
- }
70
- setData(result);
71
- setError(null);
72
- } catch (e) {
73
- setError(e);
74
- }
75
- }
76
- };
77
- } else {
78
- // Notify suspense is required
79
- throw createSuspendingPromise(watchedQuery!);
80
- }
81
- };
@@ -1,36 +0,0 @@
1
- import { CompilableQuery } from '@powersync/common';
2
- import { generateQueryKey, getQueryStore } from '../../QueryStore.js';
3
- import { usePowerSync } from '../PowerSyncContext.js';
4
- import { AdditionalOptions } from '../watched/watch-types.js';
5
- import { constructCompatibleQuery } from '../watched/watch-utils.js';
6
- import { useWatchedQuerySuspenseSubscription } from './useWatchedQuerySuspenseSubscription.js';
7
-
8
- /**
9
- * @internal This is not exported in the index.ts
10
- */
11
- export const useWatchedSuspenseQuery = <T = any>(
12
- query: string | CompilableQuery<T>,
13
- parameters: any[] = [],
14
- options: AdditionalOptions = {}
15
- ) => {
16
- const powerSync = usePowerSync();
17
- if (!powerSync) {
18
- throw new Error('PowerSync not configured.');
19
- }
20
-
21
- // Note, we don't need to check if the query changed since we fetch the WatchedQuery
22
- // from the store given these query params
23
- const { parsedQuery } = constructCompatibleQuery(query, parameters, options);
24
- const { sql: parsedSql, parameters: parsedParameters } = parsedQuery.compile();
25
-
26
- const key = generateQueryKey(parsedSql, parsedParameters, options);
27
-
28
- // When the component is suspended, all state is discarded. We don't get
29
- // any notification of that. So checkoutQuery reserves a temporary hold
30
- // on the query.
31
- // Once the component "commits", we exchange that for a permanent hold.
32
- const store = getQueryStore(powerSync);
33
- const watchedQuery = store.getQuery(key, parsedQuery, options);
34
-
35
- return useWatchedQuerySuspenseSubscription(watchedQuery);
36
- };
@@ -1,67 +0,0 @@
1
- import React from 'react';
2
- import { QueryResult } from './watch-types.js';
3
- import { InternalHookOptions } from './watch-utils.js';
4
-
5
- /**
6
- * @internal not exported from `index.ts`
7
- */
8
- export const useSingleQuery = <RowType = any>(options: InternalHookOptions<RowType[]>): QueryResult<RowType> => {
9
- const { query, powerSync, queryChanged, active } = options;
10
-
11
- const [output, setOutputState] = React.useState<QueryResult<RowType>>({
12
- isLoading: true,
13
- isFetching: true,
14
- data: [],
15
- error: undefined
16
- });
17
-
18
- const runQuery = React.useCallback(
19
- async (signal?: AbortSignal) => {
20
- setOutputState((prev) => ({ ...prev, isLoading: true, isFetching: true, error: undefined }));
21
- try {
22
- const compiledQuery = query.compile();
23
- const result = await query.execute({
24
- sql: compiledQuery.sql,
25
- parameters: [...compiledQuery.parameters],
26
- db: powerSync
27
- });
28
- if (signal.aborted) {
29
- return;
30
- }
31
- setOutputState((prev) => ({
32
- ...prev,
33
- isLoading: false,
34
- isFetching: false,
35
- data: result,
36
- error: undefined
37
- }));
38
- } catch (error) {
39
- setOutputState((prev) => ({
40
- ...prev,
41
- isLoading: false,
42
- isFetching: false,
43
- data: [],
44
- error
45
- }));
46
- }
47
- },
48
- [queryChanged, query]
49
- );
50
-
51
- // Trigger initial query execution
52
- // @ts-ignore: Complains about not all code paths returning a value
53
- React.useEffect(() => {
54
- if (active) {
55
- const abortController = new AbortController();
56
- runQuery(abortController.signal);
57
- return () => {
58
- abortController.abort();
59
- };
60
- }
61
- }, [powerSync, active, queryChanged]);
62
-
63
- return {
64
- ...output,
65
- refresh: runQuery
66
- };
67
- };
@@ -1,93 +0,0 @@
1
- import React from 'react';
2
- import { useNullableWatchedQuerySubscription } from './useWatchedQuerySubscription.js';
3
- import { DifferentialHookOptions, QueryResult, ReadonlyQueryResult } from './watch-types.js';
4
- import { InternalHookOptions } from './watch-utils.js';
5
-
6
- /**
7
- * @internal This is not exported from the index.ts
8
- *
9
- * When an incremental query is used the return type is readonly. This is required
10
- * since the implementation requires a stable ref.
11
- * For legacy compatibility we allow mutating when a standard query is used. Mutations should
12
- * not affect the internal implementation in this case.
13
- */
14
- export const useWatchedQuery = <RowType = unknown>(
15
- options: InternalHookOptions<RowType[]> & { options: DifferentialHookOptions<RowType> }
16
- ): QueryResult<RowType> | ReadonlyQueryResult<RowType> => {
17
- const { query, powerSync, queryChanged, options: hookOptions, active } = options;
18
-
19
- function createWatchedQuery() {
20
- if (!active) {
21
- return null;
22
- }
23
-
24
- const watch = hookOptions.rowComparator
25
- ? powerSync.customQuery(query).differentialWatch({
26
- rowComparator: hookOptions.rowComparator,
27
- reportFetching: hookOptions.reportFetching,
28
- throttleMs: hookOptions.throttleMs
29
- })
30
- : powerSync.customQuery(query).watch({
31
- reportFetching: hookOptions.reportFetching,
32
- throttleMs: hookOptions.throttleMs
33
- });
34
- return watch;
35
- }
36
-
37
- const [watchedQuery, setWatchedQuery] = React.useState(createWatchedQuery);
38
- const disposePendingUpdateListener = React.useRef<() => void | null>(null);
39
-
40
- React.useEffect(() => {
41
- watchedQuery?.close();
42
- const newQuery = createWatchedQuery();
43
- setWatchedQuery(newQuery);
44
-
45
- return () => {
46
- disposePendingUpdateListener.current?.();
47
- newQuery?.close();
48
- };
49
- }, [powerSync, active]);
50
-
51
- /**
52
- * Indicates that the query will be re-fetched due to a change in the query.
53
- * We execute this in-line (not using an effect) since effects are delayed till after the hook returns.
54
- * The `queryChanged` value should only be true for a single render.
55
- * The `updateSettings` method is asynchronous, thus it will update the state asynchronously.
56
- * In the React hooks we'd like to report that we are fetching the data for an updated query
57
- * as soon as the query has been updated. This prevents a result flow where e.g. the hook:
58
- * - already returned a result: isLoading, isFetching are both false
59
- * - the query is updated, but the state is still isFetching=false from the previous state
60
- * We override the isFetching status while the `updateSettings` method is running (if we report `isFetching`),
61
- * we override this value just until the `updateSettings` method itself will update the `isFetching` status.
62
- * We achieve this by registering a `settingsWillUpdate` listener on the `WatchedQuery`. This will fire
63
- * just before the `isFetching` status is updated.
64
- */
65
- if (queryChanged) {
66
- // Keep track of this pending operation
67
- watchedQuery?.updateSettings({
68
- query,
69
- throttleMs: hookOptions.throttleMs,
70
- reportFetching: hookOptions.reportFetching
71
- });
72
- // This could have been called multiple times, clear any old listeners.
73
- disposePendingUpdateListener.current?.();
74
- disposePendingUpdateListener.current = watchedQuery?.registerListener({
75
- settingsWillUpdate: () => {
76
- // We'll use the fact that we have a listener at all as an indication
77
- disposePendingUpdateListener.current?.();
78
- disposePendingUpdateListener.current = null;
79
- }
80
- });
81
- }
82
-
83
- const shouldReportCurrentlyFetching = (hookOptions.reportFetching ?? true) && !!disposePendingUpdateListener.current;
84
- const result = useNullableWatchedQuerySubscription(watchedQuery);
85
-
86
- // Result is only undefined when there is no data available yet, defaults are defined accordingly
87
- return {
88
- data: result?.data ?? [],
89
- isLoading: result?.isLoading ?? true,
90
- error: result?.error,
91
- isFetching: result?.isFetching || shouldReportCurrentlyFetching
92
- };
93
- };