@powersync/react 0.0.0-dev-20251001121637 → 0.0.0-dev-20251106124255

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 (64) 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.d.ts +31 -0
  12. package/lib/hooks/streams.js +93 -0
  13. package/lib/hooks/streams.js.map +1 -0
  14. package/lib/hooks/suspense/SuspenseQueryResult.js +1 -0
  15. package/lib/hooks/suspense/SuspenseQueryResult.js.map +1 -0
  16. package/lib/hooks/suspense/suspense-utils.js +1 -0
  17. package/lib/hooks/suspense/suspense-utils.js.map +1 -0
  18. package/lib/hooks/suspense/useSingleSuspenseQuery.js +1 -0
  19. package/lib/hooks/suspense/useSingleSuspenseQuery.js.map +1 -0
  20. package/lib/hooks/suspense/useSuspenseQuery.js +1 -0
  21. package/lib/hooks/suspense/useSuspenseQuery.js.map +1 -0
  22. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js +1 -0
  23. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js.map +1 -0
  24. package/lib/hooks/suspense/useWatchedSuspenseQuery.js +1 -0
  25. package/lib/hooks/suspense/useWatchedSuspenseQuery.js.map +1 -0
  26. package/lib/hooks/useStatus.js +1 -0
  27. package/lib/hooks/useStatus.js.map +1 -0
  28. package/lib/hooks/watched/useQuery.js +15 -4
  29. package/lib/hooks/watched/useQuery.js.map +1 -0
  30. package/lib/hooks/watched/useSingleQuery.js +1 -0
  31. package/lib/hooks/watched/useSingleQuery.js.map +1 -0
  32. package/lib/hooks/watched/useWatchedQuery.js +1 -0
  33. package/lib/hooks/watched/useWatchedQuery.js.map +1 -0
  34. package/lib/hooks/watched/useWatchedQuerySubscription.js +1 -0
  35. package/lib/hooks/watched/useWatchedQuerySubscription.js.map +1 -0
  36. package/lib/hooks/watched/watch-types.d.ts +25 -0
  37. package/lib/hooks/watched/watch-types.js +1 -0
  38. package/lib/hooks/watched/watch-types.js.map +1 -0
  39. package/lib/hooks/watched/watch-utils.js +1 -0
  40. package/lib/hooks/watched/watch-utils.js.map +1 -0
  41. package/lib/index.d.ts +1 -0
  42. package/lib/index.js +2 -0
  43. package/lib/index.js.map +1 -0
  44. package/package.json +8 -7
  45. package/src/QueryStore.ts +81 -0
  46. package/src/hooks/PowerSyncContext.ts +22 -0
  47. package/src/hooks/deprecated/usePowerSyncQuery.ts +28 -0
  48. package/src/hooks/deprecated/usePowerSyncStatus.ts +33 -0
  49. package/src/hooks/deprecated/usePowerSyncWatchedQuery.ts +60 -0
  50. package/src/hooks/streams.ts +131 -0
  51. package/src/hooks/suspense/SuspenseQueryResult.ts +4 -0
  52. package/src/hooks/suspense/suspense-utils.ts +86 -0
  53. package/src/hooks/suspense/useSingleSuspenseQuery.ts +81 -0
  54. package/src/hooks/suspense/useSuspenseQuery.ts +76 -0
  55. package/src/hooks/suspense/useWatchedQuerySuspenseSubscription.ts +60 -0
  56. package/src/hooks/suspense/useWatchedSuspenseQuery.ts +36 -0
  57. package/src/hooks/useStatus.ts +17 -0
  58. package/src/hooks/watched/useQuery.ts +98 -0
  59. package/src/hooks/watched/useSingleQuery.ts +67 -0
  60. package/src/hooks/watched/useWatchedQuery.ts +89 -0
  61. package/src/hooks/watched/useWatchedQuerySubscription.ts +52 -0
  62. package/src/hooks/watched/watch-types.ts +93 -0
  63. package/src/hooks/watched/watch-utils.ts +88 -0
  64. package/src/index.ts +12 -0
@@ -0,0 +1,33 @@
1
+ import { useContext, useEffect, useState } from 'react';
2
+ import { PowerSyncContext } from '../PowerSyncContext.js';
3
+
4
+ /**
5
+ * @deprecated Use {@link useStatus} instead.
6
+ *
7
+ * Custom hook that provides access to the current status of PowerSync.
8
+ * @returns The PowerSync Database status.
9
+ * @example
10
+ * const Component = () => {
11
+ * const status = usePowerSyncStatus();
12
+ *
13
+ * return <div>
14
+ * status.connected ? 'wifi' : 'wifi-off'
15
+ * </div>
16
+ * };
17
+ */
18
+ export const usePowerSyncStatus = () => {
19
+ const powerSync = useContext(PowerSyncContext);
20
+ const [syncStatus, setSyncStatus] = useState(powerSync.currentStatus);
21
+
22
+ useEffect(() => {
23
+ const listener = powerSync.registerListener({
24
+ statusChanged: (status) => {
25
+ setSyncStatus(status);
26
+ }
27
+ });
28
+
29
+ return () => listener?.();
30
+ }, [powerSync]);
31
+
32
+ return syncStatus;
33
+ };
@@ -0,0 +1,60 @@
1
+ import { SQLWatchOptions } from '@powersync/common';
2
+ import React from 'react';
3
+ import { usePowerSync } from '../PowerSyncContext.js';
4
+
5
+ /**
6
+ * @deprecated use {@link useQuery} instead.
7
+ *
8
+ * A hook to access the results of a watched query.
9
+ * @example
10
+ * export const Component = () => {
11
+ * const lists = usePowerSyncWatchedQuery('SELECT * from lists');
12
+ *
13
+ * return <View>
14
+ * {lists.map((l) => (
15
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
16
+ * ))}
17
+ * </View>
18
+ * }
19
+ */
20
+ export const usePowerSyncWatchedQuery = <T = any>(
21
+ sqlStatement: string,
22
+ parameters: any[] = [],
23
+ options: Omit<SQLWatchOptions, 'signal'> = {}
24
+ ): T[] => {
25
+ const powerSync = usePowerSync();
26
+ if (!powerSync) {
27
+ return [];
28
+ }
29
+
30
+ const memoizedParams = React.useMemo(() => parameters, [...parameters]);
31
+ const memoizedOptions = React.useMemo(() => options, [JSON.stringify(options)]);
32
+ const [data, setData] = React.useState<T[]>([]);
33
+ const abortController = React.useRef(new AbortController());
34
+
35
+ React.useEffect(() => {
36
+ // Abort any previous watches
37
+ abortController.current?.abort();
38
+ abortController.current = new AbortController();
39
+
40
+ powerSync.watch(
41
+ sqlStatement,
42
+ parameters,
43
+ {
44
+ onResult(results) {
45
+ setData(results.rows?._array ?? []);
46
+ }
47
+ },
48
+ {
49
+ ...options,
50
+ signal: abortController.current.signal
51
+ }
52
+ );
53
+
54
+ return () => {
55
+ abortController.current?.abort();
56
+ };
57
+ }, [powerSync, sqlStatement, memoizedParams, memoizedOptions]);
58
+
59
+ return data;
60
+ };
@@ -0,0 +1,131 @@
1
+ import { useEffect, useMemo, useState } from 'react';
2
+ import { usePowerSync } from './PowerSyncContext.js';
3
+ import {
4
+ AbstractPowerSyncDatabase,
5
+ SyncStatus,
6
+ SyncStreamStatus,
7
+ SyncStreamSubscribeOptions,
8
+ SyncStreamSubscription
9
+ } from '@powersync/common';
10
+ import { useStatus } from './useStatus.js';
11
+ import { QuerySyncStreamOptions } from './watched/watch-types.js';
12
+
13
+ /**
14
+ * A sync stream to subscribe to in {@link useSyncStream}.
15
+ *
16
+ * For more details on sync streams, see the [documentation](https://docs.powersync.com/usage/sync-streams).
17
+ */
18
+ export interface UseSyncStreamOptions extends SyncStreamSubscribeOptions {
19
+ /**
20
+ * The name of the stream to subscribe to.
21
+ */
22
+ name: string;
23
+ /**
24
+ * Parameters for the stream subscription. A single stream can have multiple subscriptions with different parameter
25
+ * sets.
26
+ */
27
+ parameters?: Record<string, any> | null;
28
+ }
29
+
30
+ /**
31
+ * Creates a PowerSync stream subscription. The subscription is kept alive as long as the React component calling this
32
+ * function. When it unmounts, {@link SyncStreamSubscription.unsubscribe} is called
33
+ *
34
+ * For more details on sync streams, see the [documentation](https://docs.powersync.com/usage/sync-streams).
35
+ *
36
+ * @returns The status for that stream, or `null` if the stream is currently being resolved.
37
+ */
38
+ export function useSyncStream(options: UseSyncStreamOptions): SyncStreamStatus | null {
39
+ const { name, parameters } = options;
40
+ const db = usePowerSync();
41
+ const status = useStatus();
42
+ const [subscription, setSubscription] = useState<SyncStreamSubscription | null>(null);
43
+
44
+ useEffect(() => {
45
+ let active = true;
46
+ let subscription: SyncStreamSubscription | null = null;
47
+
48
+ db.syncStream(name, parameters)
49
+ .subscribe(options)
50
+ .then((sub) => {
51
+ if (active) {
52
+ subscription = sub;
53
+ setSubscription(sub);
54
+ } else {
55
+ // The cleanup function already ran, unsubscribe immediately.
56
+ sub.unsubscribe();
57
+ }
58
+ });
59
+
60
+ return () => {
61
+ active = false;
62
+ // If we don't have a subscription yet, it'll still get cleaned up once the promise resolves because we've set
63
+ // active to false.
64
+ subscription?.unsubscribe();
65
+ };
66
+ }, [name, parameters]);
67
+
68
+ return subscription && status.forStream(subscription);
69
+ }
70
+
71
+ /**
72
+ * @internal
73
+ */
74
+ export function useAllSyncStreamsHaveSynced(
75
+ db: AbstractPowerSyncDatabase,
76
+ streams: QuerySyncStreamOptions[] | undefined
77
+ ): boolean {
78
+ // Since streams are a user-supplied array, they will likely be different each time this function is called. We don't
79
+ // want to update underlying subscriptions each time, though.
80
+ const hash = useMemo(() => streams && JSON.stringify(streams), [streams]);
81
+ const [synced, setHasSynced] = useState(streams == null || streams.every((e) => e.waitForStream != true));
82
+
83
+ useEffect(() => {
84
+ if (streams) {
85
+ setHasSynced(false);
86
+
87
+ const promises: Promise<SyncStreamSubscription>[] = [];
88
+ const abort = new AbortController();
89
+ for (const stream of streams) {
90
+ promises.push(db.syncStream(stream.name, stream.parameters).subscribe(stream));
91
+ }
92
+
93
+ // First, wait for all subscribe() calls to make all subscriptions active.
94
+ Promise.all(promises).then(async (resolvedStreams) => {
95
+ function allHaveSynced(status: SyncStatus) {
96
+ return resolvedStreams.every((s, i) => {
97
+ const request = streams[i];
98
+ return !request.waitForStream || status.forStream(s)?.subscription?.hasSynced;
99
+ });
100
+ }
101
+
102
+ // Wait for the effect to be cancelled or all streams having synced.
103
+ await db.waitForStatus(allHaveSynced, abort.signal);
104
+ if (abort.signal.aborted) {
105
+ // Was cancelled
106
+ } else {
107
+ // Has synced, update public state.
108
+ setHasSynced(true);
109
+
110
+ // Wait for cancellation before clearing subscriptions.
111
+ await new Promise<void>((resolve) => {
112
+ abort.signal.addEventListener('abort', () => resolve());
113
+ });
114
+ }
115
+
116
+ // Effect was definitely cancelled at this point, so drop the subscriptions.
117
+ for (const stream of resolvedStreams) {
118
+ stream.unsubscribe();
119
+ }
120
+ });
121
+
122
+ return () => abort.abort();
123
+ } else {
124
+ // There are no streams, so all of them have synced.
125
+ setHasSynced(true);
126
+ return undefined;
127
+ }
128
+ }, [hash]);
129
+
130
+ return synced;
131
+ }
@@ -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 };