@powersync/react 0.0.0-dev-20251003085035 → 0.0.0-dev-20251111122755

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 (61) hide show
  1. package/lib/QueryStore.js +1 -0
  2. package/lib/QueryStore.js.map +1 -0
  3. package/lib/hooks/PowerSyncContext.js +1 -0
  4. package/lib/hooks/PowerSyncContext.js.map +1 -0
  5. package/lib/hooks/deprecated/usePowerSyncQuery.js +1 -0
  6. package/lib/hooks/deprecated/usePowerSyncQuery.js.map +1 -0
  7. package/lib/hooks/deprecated/usePowerSyncStatus.js +1 -0
  8. package/lib/hooks/deprecated/usePowerSyncStatus.js.map +1 -0
  9. package/lib/hooks/deprecated/usePowerSyncWatchedQuery.js +1 -0
  10. package/lib/hooks/deprecated/usePowerSyncWatchedQuery.js.map +1 -0
  11. package/lib/hooks/streams.js +1 -0
  12. package/lib/hooks/streams.js.map +1 -0
  13. package/lib/hooks/suspense/SuspenseQueryResult.js +1 -0
  14. package/lib/hooks/suspense/SuspenseQueryResult.js.map +1 -0
  15. package/lib/hooks/suspense/suspense-utils.js +1 -0
  16. package/lib/hooks/suspense/suspense-utils.js.map +1 -0
  17. package/lib/hooks/suspense/useSingleSuspenseQuery.js +1 -0
  18. package/lib/hooks/suspense/useSingleSuspenseQuery.js.map +1 -0
  19. package/lib/hooks/suspense/useSuspenseQuery.js +1 -0
  20. package/lib/hooks/suspense/useSuspenseQuery.js.map +1 -0
  21. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js +1 -0
  22. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js.map +1 -0
  23. package/lib/hooks/suspense/useWatchedSuspenseQuery.js +1 -0
  24. package/lib/hooks/suspense/useWatchedSuspenseQuery.js.map +1 -0
  25. package/lib/hooks/useStatus.js +1 -0
  26. package/lib/hooks/useStatus.js.map +1 -0
  27. package/lib/hooks/watched/useQuery.js +1 -0
  28. package/lib/hooks/watched/useQuery.js.map +1 -0
  29. package/lib/hooks/watched/useSingleQuery.js +1 -0
  30. package/lib/hooks/watched/useSingleQuery.js.map +1 -0
  31. package/lib/hooks/watched/useWatchedQuery.js +1 -0
  32. package/lib/hooks/watched/useWatchedQuery.js.map +1 -0
  33. package/lib/hooks/watched/useWatchedQuerySubscription.js +1 -0
  34. package/lib/hooks/watched/useWatchedQuerySubscription.js.map +1 -0
  35. package/lib/hooks/watched/watch-types.js +1 -0
  36. package/lib/hooks/watched/watch-types.js.map +1 -0
  37. package/lib/hooks/watched/watch-utils.js +1 -0
  38. package/lib/hooks/watched/watch-utils.js.map +1 -0
  39. package/lib/index.js +1 -0
  40. package/lib/index.js.map +1 -0
  41. package/package.json +8 -7
  42. package/src/QueryStore.ts +81 -0
  43. package/src/hooks/PowerSyncContext.ts +22 -0
  44. package/src/hooks/deprecated/usePowerSyncQuery.ts +28 -0
  45. package/src/hooks/deprecated/usePowerSyncStatus.ts +33 -0
  46. package/src/hooks/deprecated/usePowerSyncWatchedQuery.ts +60 -0
  47. package/src/hooks/streams.ts +131 -0
  48. package/src/hooks/suspense/SuspenseQueryResult.ts +4 -0
  49. package/src/hooks/suspense/suspense-utils.ts +86 -0
  50. package/src/hooks/suspense/useSingleSuspenseQuery.ts +81 -0
  51. package/src/hooks/suspense/useSuspenseQuery.ts +76 -0
  52. package/src/hooks/suspense/useWatchedQuerySuspenseSubscription.ts +60 -0
  53. package/src/hooks/suspense/useWatchedSuspenseQuery.ts +36 -0
  54. package/src/hooks/useStatus.ts +17 -0
  55. package/src/hooks/watched/useQuery.ts +98 -0
  56. package/src/hooks/watched/useSingleQuery.ts +67 -0
  57. package/src/hooks/watched/useWatchedQuery.ts +89 -0
  58. package/src/hooks/watched/useWatchedQuerySubscription.ts +52 -0
  59. package/src/hooks/watched/watch-types.ts +93 -0
  60. package/src/hooks/watched/watch-utils.ts +88 -0
  61. package/src/index.ts +12 -0
@@ -0,0 +1,4 @@
1
+ import { QueryResult, ReadonlyQueryResult } from '../watched/watch-types.js';
2
+
3
+ export type SuspenseQueryResult<T> = Pick<QueryResult<T>, 'data' | 'refresh'>;
4
+ export type ReadonlySuspenseQueryResult<T> = Pick<ReadonlyQueryResult<T>, 'data' | 'refresh'>;
@@ -0,0 +1,86 @@
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
+ };
@@ -0,0 +1,81 @@
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
+ };
@@ -0,0 +1,76 @@
1
+ import { CompilableQuery } from '@powersync/common';
2
+ import { AdditionalOptions, DifferentialHookOptions } from '../watched/watch-types.js';
3
+ import { ReadonlySuspenseQueryResult, SuspenseQueryResult } from './SuspenseQueryResult.js';
4
+ import { useSingleSuspenseQuery } from './useSingleSuspenseQuery.js';
5
+ import { useWatchedSuspenseQuery } from './useWatchedSuspenseQuery.js';
6
+
7
+ /**
8
+ * A hook to access the results of a watched query that suspends until the initial result has loaded.
9
+ * @example
10
+ * export const ContentComponent = () => {
11
+ * // The lists array here will be a new Array reference whenever a change to the
12
+ * // lists table is made.
13
+ * const { data: lists } = useSuspenseQuery('SELECT * from lists');
14
+ *
15
+ * return <View>
16
+ * {lists.map((l) => (
17
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
18
+ * ))}
19
+ * </View>;
20
+ * }
21
+ *
22
+ * export const DisplayComponent = () => {
23
+ * return (
24
+ * <Suspense fallback={<div>Loading content...</div>}>
25
+ * <ContentComponent />
26
+ * </Suspense>
27
+ * );
28
+ * }
29
+ *
30
+ * export const DiffContentComponent = () => {
31
+ * // A differential query will emit results when a change to the result set occurs.
32
+ * // The internal array object references are maintained for unchanged rows.
33
+ * // The returned lists array is read only when a `rowComparator` is provided.
34
+ * const { data: lists } = useSuspenseQuery('SELECT * from lists', [], {
35
+ * rowComparator: {
36
+ * keyBy: (item) => item.id,
37
+ * compareBy: (item) => JSON.stringify(item)
38
+ * }
39
+ * });
40
+ * return <View>
41
+ * {lists.map((l) => (
42
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
43
+ * ))}
44
+ * </View>;
45
+ * }
46
+ *
47
+ * export const DisplayComponent = () => {
48
+ * return (
49
+ * <Suspense fallback={<div>Loading content...</div>}>
50
+ * <ContentComponent />
51
+ * </Suspense>
52
+ * );
53
+ * }
54
+ */
55
+ export function useSuspenseQuery<RowType = any>(
56
+ query: string | CompilableQuery<RowType>,
57
+ parameters?: any[],
58
+ options?: AdditionalOptions
59
+ ): SuspenseQueryResult<RowType>;
60
+ export function useSuspenseQuery<RowType = any>(
61
+ query: string | CompilableQuery<RowType>,
62
+ paramerers?: any[],
63
+ options?: DifferentialHookOptions<RowType>
64
+ ): ReadonlySuspenseQueryResult<RowType>;
65
+ export function useSuspenseQuery<RowType = any>(
66
+ query: string | CompilableQuery<RowType>,
67
+ parameters: any[] = [],
68
+ options: AdditionalOptions & DifferentialHookOptions<RowType> = {}
69
+ ) {
70
+ switch (options?.runQueryOnce) {
71
+ case true:
72
+ return useSingleSuspenseQuery<RowType>(query, parameters, options);
73
+ default:
74
+ return useWatchedSuspenseQuery<RowType>(query, parameters, options);
75
+ }
76
+ }
@@ -0,0 +1,60 @@
1
+ import { WatchedQuery } from '@powersync/common';
2
+ import React from 'react';
3
+ import { createSuspendingPromise, useTemporaryHold } from './suspense-utils.js';
4
+
5
+ /**
6
+ * A hook to access and subscribe to the results of an existing {@link WatchedQuery}.
7
+ * @example
8
+ * export const ContentComponent = () => {
9
+ * const { data: lists } = useWatchedQuerySuspenseSubscription(listsQuery);
10
+ *
11
+ * return <View>
12
+ * {lists.map((l) => (
13
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
14
+ * ))}
15
+ * </View>;
16
+ * }
17
+ *
18
+ * export const DisplayComponent = () => {
19
+ * return (
20
+ * <Suspense fallback={<div>Loading content...</div>}>
21
+ * <ContentComponent />
22
+ * </Suspense>
23
+ * );
24
+ * }
25
+ */
26
+ export const useWatchedQuerySuspenseSubscription = <
27
+ ResultType = unknown,
28
+ Query extends WatchedQuery<ResultType> = WatchedQuery<ResultType>
29
+ >(
30
+ query: Query
31
+ ): Query['state'] => {
32
+ useTemporaryHold(query);
33
+
34
+ // Force update state function
35
+ const [, setUpdateCounter] = React.useState(0);
36
+
37
+ React.useEffect(() => {
38
+ // This runs when the component came out of suspense
39
+ // This add a permanent hold since a listener has been added to the query
40
+ const dispose = query.registerListener({
41
+ onStateChange() {
42
+ // Trigger rerender
43
+ setUpdateCounter((prev) => prev + 1);
44
+ }
45
+ });
46
+
47
+ return dispose;
48
+ }, []);
49
+
50
+ if (query.state.error != null) {
51
+ // Report errors - this is caught by an error boundary
52
+ throw query.state.error;
53
+ } else if (!query.state.isLoading) {
54
+ // Happy path data return
55
+ return query.state;
56
+ } else {
57
+ // Notify suspense is required
58
+ throw createSuspendingPromise(query);
59
+ }
60
+ };
@@ -0,0 +1,36 @@
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
+ };
@@ -0,0 +1,17 @@
1
+ import { usePowerSyncStatus } from './deprecated/usePowerSyncStatus.js';
2
+
3
+ /**
4
+ * Custom hook that provides access to the current status of PowerSync.
5
+ * @returns The PowerSync Database status.
6
+ * @example
7
+ * import { useStatus } from "@powersync/react";
8
+ *
9
+ * const Component = () => {
10
+ * const status = useStatus();
11
+ *
12
+ * return <div>
13
+ * status.connected ? 'wifi' : 'wifi-off'
14
+ * </div>
15
+ * };
16
+ */
17
+ export const useStatus = () => usePowerSyncStatus();
@@ -0,0 +1,98 @@
1
+ import { type CompilableQuery } from '@powersync/common';
2
+ import { usePowerSync } from '../PowerSyncContext.js';
3
+ import { useSingleQuery } from './useSingleQuery.js';
4
+ import { useWatchedQuery } from './useWatchedQuery.js';
5
+ import { AdditionalOptions, DifferentialHookOptions, QueryResult, ReadonlyQueryResult } from './watch-types.js';
6
+ import { constructCompatibleQuery } from './watch-utils.js';
7
+ import { useAllSyncStreamsHaveSynced } from '../streams.js';
8
+
9
+ /**
10
+ * A hook to access the results of a watched query.
11
+ * @example
12
+ *
13
+ * export const Component = () => {
14
+ * // The lists array here will be a new Array reference whenever a change to the
15
+ * // lists table is made.
16
+ * const { data: lists } = useQuery('SELECT * from lists');
17
+ *
18
+ * return <View>
19
+ * {lists.map((l) => (
20
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
21
+ * ))}
22
+ * </View>
23
+ * }
24
+ *
25
+ * export const DiffComponent = () => {
26
+ * // Providing a `rowComparator` results in the hook using an incremental query under the hood.
27
+ * // An incremental query will only emit results when a change to the result set occurs.
28
+ * // The internal array object references are maintained for unchanged rows.
29
+ * // The returned lists array is read only when a `rowComparator` is provided.
30
+ * const { data: lists } = useQuery('SELECT * from lists', [], {
31
+ * rowComparator: {
32
+ * keyBy: (item) => item.id,
33
+ * compareBy: (item) => JSON.stringify(item)
34
+ * }
35
+ * });
36
+ *
37
+ * return <View>
38
+ * {lists.map((l) => (
39
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
40
+ * ))}
41
+ * </View>
42
+ * }
43
+ */
44
+
45
+ export function useQuery<RowType = any>(
46
+ query: string | CompilableQuery<RowType>,
47
+ parameters?: any[],
48
+ options?: AdditionalOptions
49
+ ): QueryResult<RowType>;
50
+ export function useQuery<RowType = any>(
51
+ query: string | CompilableQuery<RowType>,
52
+ parameters?: any[],
53
+ options?: DifferentialHookOptions<RowType>
54
+ ): ReadonlyQueryResult<RowType>;
55
+ export function useQuery<RowType = any>(
56
+ query: string | CompilableQuery<RowType>,
57
+ parameters: any[] = [],
58
+ options: AdditionalOptions & DifferentialHookOptions<RowType> = {}
59
+ ) {
60
+ const powerSync = usePowerSync();
61
+ if (!powerSync) {
62
+ return {
63
+ ..._loadingState,
64
+ isLoading: false,
65
+ error: new Error('PowerSync not configured.')
66
+ };
67
+ }
68
+ const { parsedQuery, queryChanged } = constructCompatibleQuery(query, parameters, options);
69
+ const streamsHaveSynced = useAllSyncStreamsHaveSynced(powerSync, options?.streams);
70
+ const runOnce = options?.runQueryOnce == true;
71
+ const single = useSingleQuery<RowType>({
72
+ query: parsedQuery,
73
+ powerSync,
74
+ queryChanged,
75
+ active: runOnce && streamsHaveSynced
76
+ });
77
+ const watched = useWatchedQuery<RowType>({
78
+ query: parsedQuery,
79
+ powerSync,
80
+ queryChanged,
81
+ options: {
82
+ reportFetching: options.reportFetching,
83
+ // Maintains backwards compatibility with previous versions
84
+ // Differentiation is opt-in by default
85
+ // We emit new data for each table change by default.
86
+ rowComparator: options.rowComparator
87
+ },
88
+ active: !runOnce && streamsHaveSynced
89
+ });
90
+
91
+ if (!streamsHaveSynced) {
92
+ return { ..._loadingState };
93
+ }
94
+
95
+ return (runOnce ? single : watched) ?? _loadingState;
96
+ }
97
+
98
+ const _loadingState = { isLoading: true, isFetching: false, data: [], error: undefined };
@@ -0,0 +1,67 @@
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
+ };
@@ -0,0 +1,89 @@
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
+ return {
86
+ ...result,
87
+ isFetching: result?.isFetching || shouldReportCurrentlyFetching
88
+ };
89
+ };
@@ -0,0 +1,52 @@
1
+ import { WatchedQuery } from '@powersync/common';
2
+ import React from 'react';
3
+
4
+ /**
5
+ * A hook to access and subscribe to the results of an existing {@link WatchedQuery} instance.
6
+ * @example
7
+ * export const ContentComponent = () => {
8
+ * const { data: lists } = useWatchedQuerySubscription(listsQuery);
9
+ *
10
+ * return <View>
11
+ * {lists.map((l) => (
12
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
13
+ * ))}
14
+ * </View>;
15
+ * }
16
+ *
17
+ */
18
+ export const useWatchedQuerySubscription = <
19
+ ResultType = unknown,
20
+ Query extends WatchedQuery<ResultType> = WatchedQuery<ResultType>
21
+ >(
22
+ query: Query
23
+ ): Query['state'] => {
24
+ return useNullableWatchedQuerySubscription(query);
25
+ };
26
+
27
+ /**
28
+ * @internal
29
+ */
30
+ export const useNullableWatchedQuerySubscription = <
31
+ ResultType = unknown,
32
+ Query extends WatchedQuery<ResultType> = WatchedQuery<ResultType>
33
+ >(
34
+ query: Query | null
35
+ ): Query['state'] | undefined => {
36
+ const [output, setOutputState] = React.useState(query?.state);
37
+
38
+ // @ts-ignore: Complains about not all code paths returning a value
39
+ React.useEffect(() => {
40
+ if (query) {
41
+ setOutputState(query.state);
42
+
43
+ return query.registerListener({
44
+ onStateChange: (state) => {
45
+ setOutputState({ ...state });
46
+ }
47
+ });
48
+ }
49
+ }, [query]);
50
+
51
+ return output;
52
+ };