@powersync/react 0.0.0-dev-20250310145419 → 0.0.0-dev-20250714151300

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 (43) hide show
  1. package/README.md +121 -1
  2. package/lib/QueryStore.d.ts +5 -6
  3. package/lib/QueryStore.js +32 -6
  4. package/lib/hooks/{usePowerSyncQuery.js → deprecated/usePowerSyncQuery.js} +1 -1
  5. package/lib/hooks/{usePowerSyncStatus.js → deprecated/usePowerSyncStatus.js} +1 -1
  6. package/lib/hooks/{usePowerSyncWatchedQuery.js → deprecated/usePowerSyncWatchedQuery.js} +1 -1
  7. package/lib/hooks/suspense/SuspenseQueryResult.d.ts +3 -0
  8. package/lib/hooks/suspense/SuspenseQueryResult.js +1 -0
  9. package/lib/hooks/suspense/suspense-utils.d.ts +19 -0
  10. package/lib/hooks/suspense/suspense-utils.js +78 -0
  11. package/lib/hooks/suspense/useSingleSuspenseQuery.d.ts +10 -0
  12. package/lib/hooks/suspense/useSingleSuspenseQuery.js +75 -0
  13. package/lib/hooks/suspense/useSuspenseQuery.d.ts +53 -0
  14. package/lib/hooks/suspense/useSuspenseQuery.js +10 -0
  15. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.d.ts +23 -0
  16. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js +56 -0
  17. package/lib/hooks/suspense/useWatchedSuspenseQuery.d.ts +6 -0
  18. package/lib/hooks/suspense/useWatchedSuspenseQuery.js +25 -0
  19. package/lib/hooks/useStatus.js +2 -2
  20. package/lib/hooks/watched/useQuery.d.ts +38 -0
  21. package/lib/hooks/watched/useQuery.js +32 -0
  22. package/lib/hooks/watched/useSingleQuery.d.ts +3 -0
  23. package/lib/hooks/watched/useSingleQuery.js +52 -0
  24. package/lib/hooks/watched/useWatchedQuery.d.ts +13 -0
  25. package/lib/hooks/watched/useWatchedQuery.js +43 -0
  26. package/lib/hooks/watched/useWatchedQuerySubscription.d.ts +16 -0
  27. package/lib/hooks/watched/useWatchedQuerySubscription.js +29 -0
  28. package/lib/hooks/watched/watch-types.d.ts +60 -0
  29. package/lib/hooks/watched/watch-types.js +1 -0
  30. package/lib/hooks/watched/watch-utils.d.ts +12 -0
  31. package/lib/hooks/watched/watch-utils.js +56 -0
  32. package/lib/index.d.ts +9 -5
  33. package/lib/index.js +7 -5
  34. package/package.json +8 -5
  35. package/lib/WatchedQuery.d.ts +0 -35
  36. package/lib/WatchedQuery.js +0 -145
  37. package/lib/hooks/useQuery.d.ts +0 -34
  38. package/lib/hooks/useQuery.js +0 -125
  39. package/lib/hooks/useSuspenseQuery.d.ts +0 -25
  40. package/lib/hooks/useSuspenseQuery.js +0 -74
  41. /package/lib/hooks/{usePowerSyncQuery.d.ts → deprecated/usePowerSyncQuery.d.ts} +0 -0
  42. /package/lib/hooks/{usePowerSyncStatus.d.ts → deprecated/usePowerSyncStatus.d.ts} +0 -0
  43. /package/lib/hooks/{usePowerSyncWatchedQuery.d.ts → deprecated/usePowerSyncWatchedQuery.d.ts} +0 -0
package/README.md CHANGED
@@ -69,7 +69,7 @@ const Component = () => {
69
69
 
70
70
  ## Reactive Queries
71
71
 
72
- The `useQuery` hook allows you to access the results of a watched query. Queries will automatically update when a dependant table is updated unless you set the `runQueryOnce` flag. You are also able to use a compilable query (e.g. [Kysely queries](https://github.com/powersync-ja/powersync-js/tree/main/packages/kysely-driver)) as a query argument in place of a SQL statement string.
72
+ The `useQuery` hook allows you to access the results of a watched query. Queries will automatically update when a dependent table is updated unless you set the `runQueryOnce` flag. You are also able to use a compilable query (e.g. [Kysely queries](https://github.com/powersync-ja/powersync-js/tree/main/packages/kysely-driver)) as a query argument in place of a SQL statement string.
73
73
 
74
74
  ```JSX
75
75
  // TodoListDisplay.jsx
@@ -271,3 +271,123 @@ export const TodoListDisplaySuspense = () => {
271
271
  );
272
272
  };
273
273
  ```
274
+
275
+ ## Preventing Unnecessary Renders
276
+
277
+ The `useQuery` hook returns a stateful object which contains query fetching/loading state values and the query result set data.
278
+
279
+ ```tsx
280
+ function MyWidget() {
281
+ // ... Widget code
282
+ // result is an object which contains `isLoading`, `isFetching`, `data` members.
283
+ const result = useQuery(...)
284
+
285
+ // ... Widget code
286
+ }
287
+ ```
288
+
289
+ ### High Order Components
290
+
291
+ The returned object is a new JS object reference whenever the internal state changes e.g. if the query `isFetching` alternates in value. The parent component which calls `useQuery` will render each time the watched query state changes - this can result in other child widgets re-rendering if they are not memoized. Using the `result` object in child component props will cause those children to re-render on any state change of the watched query. The first step to avoid re-renders is to call `useQuery` in a Higher Order Component which passes query results to memoized children.
292
+
293
+ ```tsx
294
+ function MyWidget() {
295
+ // ... Widget code
296
+ // result is an object which contains `isLoading`, `isFetching`, `data` members.
297
+ const {data, error, isLoading} = useQuery(...)
298
+
299
+ // ... Widget code
300
+
301
+ return (
302
+ // ... Other components
303
+
304
+ // If MyWatchedWidget is not memoized
305
+ // - It will rerender on any state change of the watched query. E.g. if isFetching alternates
306
+ // If MyWatchedWidget is memoized
307
+ // - It will re-render if the data reference changes. By default the data reference changes after any
308
+ // change to the query's dependent tables. This can be optimized by using Incremental queries.
309
+ <MyWatchedWidget watchedResult={data}>
310
+ )
311
+ }
312
+ ```
313
+
314
+ ### Incremental Queries
315
+
316
+ By default watched queries are queried whenever a change to the underlying tables has been detected. These changes might not be relevant to the actual query, but will still trigger a query and `data` update.
317
+
318
+ ```tsx
319
+ function MyWidget() {
320
+ // ... Widget code
321
+ // This query will update with a new data Array whenever any change is made to the `cats` table
322
+ // E.g. `INSERT INTO cats(name) VALUES ('silvester')` will return a new Array reference for `data`
323
+ const { data } = useQuery(`SELECT * FROM cats WHERE name = 'bob'`)
324
+
325
+ // ... Widget code
326
+
327
+ return (
328
+ // Other components
329
+ // This will rerender for any change to the `cats` table
330
+ // Memoization cannot prevent this component from re-rendering since `data[0]` is always new object reference
331
+ // whenever a query has been triggered
332
+ <Cat details={data[0]}>
333
+ )
334
+ }
335
+ ```
336
+
337
+ Incremental watched queries ensure that the `data` member of the `useQuery` result maintains the same Array reference if the result set is unchanged.
338
+ Additionally, the internal array items maintain object references when unchanged.
339
+
340
+ ```tsx
341
+ function MyWidget() {
342
+ // ... Widget code
343
+ // This query will be fetched/queried whenever any change is made to the `cats` table.
344
+ // The `data` reference will only be changed if there have been changes since the previous value.
345
+ // This method performs a comparison in memory in order to determine changes.
346
+ // Note that isFetching is set (by default) whenever the query is being fetched/checked.
347
+ // This will result in `MyWidget` re-rendering for any change to the `cats` table.
348
+ const { data, isLoading, isFetching } = useQuery(`SELECT * FROM cats WHERE breed = 'tabby'`, [], {
349
+ differentiator: {
350
+ identify: (item) => item.id,
351
+ compareBy: (item) => JSON.stringify(item)
352
+ }
353
+ })
354
+
355
+ // ... Widget code
356
+
357
+ return (
358
+ // Other components
359
+ // The data array is the same reference if no changes have occurred between fetches
360
+ // Note: The array is a new reference is there are any changes in the result set (individual row object references are preserved for unchanged rows)
361
+ // Note: CatCollection requires memoization in order to prevent re-rendering (due to the parent re-rendering on fetch)
362
+ <CatCollection cats={data}>
363
+ )
364
+ }
365
+ ```
366
+
367
+ `useQuery` can be configured to disable reporting `isFetching` status. Disabling this setting reduces the number of events emitted from the hook, which can reduce renders in some circumstances.
368
+
369
+ ```tsx
370
+ function MyWidget() {
371
+ // ... Widget code
372
+ // This query will be fetched/queried whenever any change is made to the `cats` table.
373
+ // The `data` reference will only be changed if there have been changes since the previous value.
374
+ // When reportFetching == false the object returned from useQuery will only be changed when the data, isLoading or error state changes.
375
+ // This method performs a comparison in memory in order to determine changes.
376
+ const { data, isLoading } = useQuery(`SELECT * FROM cats WHERE breed = 'tabby'`, [], {
377
+ differentiator: {
378
+ identify: (item) => item.id,
379
+ compareBy: (item) => JSON.stringify(item)
380
+ }
381
+ reportFetching: false
382
+ })
383
+
384
+ // ... Widget code
385
+
386
+ return (
387
+ // Other components
388
+ // The data array is the same reference if no changes have occurred between fetches
389
+ // Note: The array is a new reference is there are any changes in the result set (individual row object references are not preserved)
390
+ <CatCollection cats={data}>
391
+ )
392
+ }
393
+ ```
@@ -1,11 +1,10 @@
1
- import { AbstractPowerSyncDatabase } from '@powersync/common';
2
- import { Query, WatchedQuery } from './WatchedQuery';
3
- import { AdditionalOptions } from './hooks/useQuery';
4
- export declare function generateQueryKey(sqlStatement: string, parameters: any[], options: AdditionalOptions): string;
1
+ import { AbstractPowerSyncDatabase, WatchCompatibleQuery, WatchedQuery } from '@powersync/common';
2
+ import { DifferentialHookOptions } from './hooks/watched/watch-types';
3
+ export declare function generateQueryKey(sqlStatement: string, parameters: ReadonlyArray<unknown>, options: DifferentialHookOptions<unknown>): string;
5
4
  export declare class QueryStore {
6
5
  private db;
7
- cache: Map<string, WatchedQuery>;
6
+ cache: Map<string, WatchedQuery<unknown, import("@powersync/common").WatchedQueryOptions, import("@powersync/common").WatchedQueryListener<unknown>>>;
8
7
  constructor(db: AbstractPowerSyncDatabase);
9
- getQuery(key: string, query: Query<unknown>, options: AdditionalOptions): WatchedQuery;
8
+ getQuery<RowType>(key: string, query: WatchCompatibleQuery<RowType[]>, options: DifferentialHookOptions<RowType>): import("@powersync/common").DifferentialWatchedQuery<RowType>;
10
9
  }
11
10
  export declare function getQueryStore(db: AbstractPowerSyncDatabase): QueryStore;
package/lib/QueryStore.js CHANGED
@@ -1,4 +1,4 @@
1
- import { WatchedQuery } from './WatchedQuery';
1
+ import { WatchedQueryListenerEvent } from '@powersync/common';
2
2
  export function generateQueryKey(sqlStatement, parameters, options) {
3
3
  return `${sqlStatement} -- ${JSON.stringify(parameters)} -- ${JSON.stringify(options)}`;
4
4
  }
@@ -12,15 +12,41 @@ export class QueryStore {
12
12
  if (this.cache.has(key)) {
13
13
  return this.cache.get(key);
14
14
  }
15
- const q = new WatchedQuery(this.db, query, options);
16
- const disposer = q.registerListener({
17
- disposed: () => {
15
+ const watch = options.differentiator
16
+ ? this.db.customQuery(query).differentialWatch({
17
+ differentiator: options.differentiator,
18
+ reportFetching: options.reportFetching,
19
+ throttleMs: options.throttleMs
20
+ })
21
+ : this.db.customQuery(query).watch({
22
+ reportFetching: options.reportFetching,
23
+ throttleMs: options.throttleMs
24
+ });
25
+ this.cache.set(key, watch);
26
+ const disposer = watch.registerListener({
27
+ closed: () => {
18
28
  this.cache.delete(key);
19
29
  disposer?.();
20
30
  }
21
31
  });
22
- this.cache.set(key, q);
23
- return q;
32
+ watch.listenerMeta.registerListener({
33
+ listenersChanged: (counts) => {
34
+ // Dispose this query if there are no subscribers present
35
+ // We don't use the total here since we don't want to consider `onclose` listeners
36
+ const relevantCounts = [
37
+ WatchedQueryListenerEvent.ON_DATA,
38
+ WatchedQueryListenerEvent.ON_STATE_CHANGE,
39
+ WatchedQueryListenerEvent.ON_ERROR
40
+ ].reduce((sum, event) => {
41
+ return sum + (counts[event] || 0);
42
+ }, 0);
43
+ if (relevantCounts == 0) {
44
+ watch.close();
45
+ this.cache.delete(key);
46
+ }
47
+ }
48
+ });
49
+ return watch;
24
50
  }
25
51
  }
26
52
  let queryStores = undefined;
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { usePowerSync } from './PowerSyncContext';
2
+ import { usePowerSync } from '../PowerSyncContext';
3
3
  /**
4
4
  * @deprecated use {@link useQuery} instead.
5
5
  *
@@ -1,5 +1,5 @@
1
1
  import { useContext, useEffect, useState } from 'react';
2
- import { PowerSyncContext } from './PowerSyncContext';
2
+ import { PowerSyncContext } from '../PowerSyncContext';
3
3
  /**
4
4
  * @deprecated Use {@link useStatus} instead.
5
5
  *
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import { usePowerSync } from './PowerSyncContext';
2
+ import { usePowerSync } from '../PowerSyncContext';
3
3
  /**
4
4
  * @deprecated use {@link useQuery} instead.
5
5
  *
@@ -0,0 +1,3 @@
1
+ import { QueryResult, ReadonlyQueryResult } from '../watched/watch-types';
2
+ export type SuspenseQueryResult<T> = Pick<QueryResult<T>, 'data' | 'refresh'>;
3
+ export type ReadonlySuspenseQueryResult<T> = Pick<ReadonlyQueryResult<T>, 'data' | 'refresh'>;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { WatchedQuery } from '@powersync/common';
2
+ /**
3
+ * The store will dispose this query if it has no subscribers attached to it.
4
+ * The suspense promise adds a subscriber to the query, but the promise could resolve
5
+ * before this component is committed. The promise will release it's listener once the query is no longer loading.
6
+ * This temporary hold is used to ensure that the query is not disposed in the interim.
7
+ * Creates a subscription for state change which creates a temporary hold on the query
8
+ * @returns a function to release the hold
9
+ */
10
+ export declare const useTemporaryHold: (watchedQuery?: WatchedQuery<unknown>) => {
11
+ releaseHold: () => void;
12
+ };
13
+ /**
14
+ * React suspense relies on a promise that resolves once the initial data has loaded.
15
+ * This creates a promise which registers a listener on the watched query.
16
+ * Registering a listener on the watched query will ensure that the query is not disposed
17
+ * while the component is suspended.
18
+ */
19
+ export declare const createSuspendingPromise: (query: WatchedQuery<unknown>) => Promise<void>;
@@ -0,0 +1,78 @@
1
+ import React from 'react';
2
+ /**
3
+ * The store will dispose this query if it has no subscribers attached to it.
4
+ * The suspense promise adds a subscriber to the query, but the promise could resolve
5
+ * before this component is committed. The promise will release it's listener once the query is no longer loading.
6
+ * This temporary hold is used to ensure that the query is not disposed in the interim.
7
+ * Creates a subscription for state change which creates a temporary hold on the query
8
+ * @returns a function to release the hold
9
+ */
10
+ export const useTemporaryHold = (watchedQuery) => {
11
+ const releaseTemporaryHold = React.useRef(undefined);
12
+ const addedHoldTo = React.useRef(undefined);
13
+ if (addedHoldTo.current !== watchedQuery) {
14
+ releaseTemporaryHold.current?.();
15
+ addedHoldTo.current = watchedQuery;
16
+ if (!watchedQuery || !watchedQuery.state.isLoading) {
17
+ // No query to hold or no reason to hold, return a no-op
18
+ return {
19
+ releaseHold: () => { }
20
+ };
21
+ }
22
+ const disposeSubscription = watchedQuery.registerListener({
23
+ onStateChange: (state) => { }
24
+ });
25
+ let timeout;
26
+ const disposeClosedListener = watchedQuery.registerListener({
27
+ closed: () => {
28
+ if (timeout) {
29
+ clearTimeout(timeout);
30
+ }
31
+ disposeClosedListener();
32
+ }
33
+ });
34
+ const releaseHold = () => {
35
+ disposeSubscription();
36
+ disposeClosedListener();
37
+ };
38
+ releaseTemporaryHold.current = releaseHold;
39
+ const timeoutPollMs = 5_000;
40
+ const checkHold = () => {
41
+ if (watchedQuery.closed || !watchedQuery.state.isLoading || watchedQuery.state.error) {
42
+ // No need to keep a temporary hold on this query
43
+ releaseHold();
44
+ }
45
+ else {
46
+ // Need to keep the hold, check again after timeout
47
+ setTimeout(checkHold, timeoutPollMs);
48
+ }
49
+ };
50
+ // Set a timeout to conditionally remove the temporary hold
51
+ setTimeout(checkHold, timeoutPollMs);
52
+ }
53
+ return {
54
+ releaseHold: releaseTemporaryHold.current
55
+ };
56
+ };
57
+ /**
58
+ * React suspense relies on a promise that resolves once the initial data has loaded.
59
+ * This creates a promise which registers a listener on the watched query.
60
+ * Registering a listener on the watched query will ensure that the query is not disposed
61
+ * while the component is suspended.
62
+ */
63
+ export const createSuspendingPromise = (query) => {
64
+ return new Promise((resolve) => {
65
+ // The listener here will dispose itself once the loading is done
66
+ // This decreases the number of listeners on the query
67
+ // even if the component is unmounted
68
+ const dispose = query.registerListener({
69
+ onStateChange: (state) => {
70
+ // Returns to the hook if loading is completed or if loading resulted in an error
71
+ if (!state.isLoading || state.error) {
72
+ resolve();
73
+ dispose();
74
+ }
75
+ }
76
+ });
77
+ });
78
+ };
@@ -0,0 +1,10 @@
1
+ import { CompilableQuery } from '@powersync/common';
2
+ import { AdditionalOptions } from '../watched/watch-types';
3
+ import { SuspenseQueryResult } from './SuspenseQueryResult';
4
+ /**
5
+ * Use a query which is not watched, but suspends until the initial result has loaded.
6
+ * Internally this uses a WatchedQuery during suspense for state management. The watched
7
+ * query is potentially disposed, if there are no subscribers attached to it, after the initial load.
8
+ * The query can be refreshed by calling the `refresh` function after initial load.
9
+ */
10
+ export declare const useSingleSuspenseQuery: <T = any>(query: string | CompilableQuery<T>, parameters?: any[], options?: AdditionalOptions) => SuspenseQueryResult<T>;
@@ -0,0 +1,75 @@
1
+ import React from 'react';
2
+ import { generateQueryKey, getQueryStore } from '../../QueryStore';
3
+ import { usePowerSync } from '../PowerSyncContext';
4
+ import { constructCompatibleQuery } from '../watched/watch-utils';
5
+ import { createSuspendingPromise, useTemporaryHold } from './suspense-utils';
6
+ /**
7
+ * Use a query which is not watched, but suspends until the initial result has loaded.
8
+ * Internally this uses a WatchedQuery during suspense for state management. The watched
9
+ * query is potentially disposed, if there are no subscribers attached to it, after the initial load.
10
+ * The query can be refreshed by calling the `refresh` function after initial load.
11
+ */
12
+ export const useSingleSuspenseQuery = (query, parameters = [], options = {}) => {
13
+ const powerSync = usePowerSync();
14
+ if (!powerSync) {
15
+ throw new Error('PowerSync not configured.');
16
+ }
17
+ // Manually track data for single queries
18
+ const [data, setData] = React.useState(null);
19
+ const [error, setError] = React.useState(null);
20
+ // Note, we don't need to check if the query changed since we fetch the WatchedQuery
21
+ // from the store given these query params
22
+ const { parsedQuery } = constructCompatibleQuery(query, parameters, options);
23
+ const { sql: parsedSql, parameters: parsedParameters } = parsedQuery.compile();
24
+ const key = generateQueryKey(parsedSql, parsedParameters, options);
25
+ const store = getQueryStore(powerSync);
26
+ // Only use a temporary watched query if we don't have data yet.
27
+ const watchedQuery = data ? null : store.getQuery(key, parsedQuery, options);
28
+ const { releaseHold } = useTemporaryHold(watchedQuery);
29
+ React.useEffect(() => {
30
+ // Set the initial yielded data
31
+ // it should be available once we commit the component
32
+ if (watchedQuery?.state.error) {
33
+ setError(watchedQuery.state.error);
34
+ }
35
+ else if (watchedQuery?.state.isLoading === false) {
36
+ setData(watchedQuery.state.data);
37
+ setError(null);
38
+ }
39
+ if (!watchedQuery?.state.isLoading) {
40
+ releaseHold();
41
+ }
42
+ }, []);
43
+ if (error != null) {
44
+ // Report errors - this is caught by an error boundary
45
+ throw error;
46
+ }
47
+ else if (data || watchedQuery?.state.isLoading === false) {
48
+ // Happy path data return
49
+ return {
50
+ data: data ?? watchedQuery?.state.data ?? [],
51
+ refresh: async (signal) => {
52
+ try {
53
+ const compiledQuery = parsedQuery.compile();
54
+ const result = await parsedQuery.execute({
55
+ sql: compiledQuery.sql,
56
+ parameters: [...compiledQuery.parameters],
57
+ db: powerSync
58
+ });
59
+ if (signal.aborted) {
60
+ return; // Abort if the signal is already aborted
61
+ }
62
+ setData(result);
63
+ setError(null);
64
+ }
65
+ catch (e) {
66
+ setError(e);
67
+ }
68
+ }
69
+ };
70
+ }
71
+ else {
72
+ // Notify suspense is required
73
+ throw createSuspendingPromise(watchedQuery);
74
+ }
75
+ };
@@ -0,0 +1,53 @@
1
+ import { CompilableQuery } from '@powersync/common';
2
+ import { AdditionalOptions, DifferentialHookOptions } from '../watched/watch-types';
3
+ import { ReadonlySuspenseQueryResult, SuspenseQueryResult } from './SuspenseQueryResult';
4
+ /**
5
+ * A hook to access the results of a watched query that suspends until the initial result has loaded.
6
+ * @example
7
+ * export const ContentComponent = () => {
8
+ * // The lists array here will be a new Array reference whenever a change to the
9
+ * // lists table is made.
10
+ * const { data: lists } = useSuspenseQuery('SELECT * from lists');
11
+ *
12
+ * return <View>
13
+ * {lists.map((l) => (
14
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
15
+ * ))}
16
+ * </View>;
17
+ * }
18
+ *
19
+ * export const DisplayComponent = () => {
20
+ * return (
21
+ * <Suspense fallback={<div>Loading content...</div>}>
22
+ * <ContentComponent />
23
+ * </Suspense>
24
+ * );
25
+ * }
26
+ *
27
+ * export const DiffContentComponent = () => {
28
+ * // A differential query will emit results when a change to the result set occurs.
29
+ * // The internal array object references are maintained for unchanged rows.
30
+ * // The returned lists array is read only when a `differentiator` is provided.
31
+ * const { data: lists } = useSuspenseQuery('SELECT * from lists', [], {
32
+ * differentiator: {
33
+ * identify: (item) => item.id,
34
+ * compareBy: (item) => JSON.stringify(item)
35
+ * }
36
+ * });
37
+ * return <View>
38
+ * {lists.map((l) => (
39
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
40
+ * ))}
41
+ * </View>;
42
+ * }
43
+ *
44
+ * export const DisplayComponent = () => {
45
+ * return (
46
+ * <Suspense fallback={<div>Loading content...</div>}>
47
+ * <ContentComponent />
48
+ * </Suspense>
49
+ * );
50
+ * }
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>;
@@ -0,0 +1,10 @@
1
+ import { useSingleSuspenseQuery } from './useSingleSuspenseQuery';
2
+ import { useWatchedSuspenseQuery } from './useWatchedSuspenseQuery';
3
+ 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);
9
+ }
10
+ }
@@ -0,0 +1,23 @@
1
+ import { WatchedQuery } from '@powersync/common';
2
+ /**
3
+ * A hook to access and subscribe to the results of an existing {@link WatchedQuery}.
4
+ * @example
5
+ * export const ContentComponent = () => {
6
+ * const { data: lists } = useWatchedQuerySuspenseSubscription(listsQuery);
7
+ *
8
+ * return <View>
9
+ * {lists.map((l) => (
10
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
11
+ * ))}
12
+ * </View>;
13
+ * }
14
+ *
15
+ * export const DisplayComponent = () => {
16
+ * return (
17
+ * <Suspense fallback={<div>Loading content...</div>}>
18
+ * <ContentComponent />
19
+ * </Suspense>
20
+ * );
21
+ * }
22
+ */
23
+ export declare const useWatchedQuerySuspenseSubscription: <ResultType = unknown, Query extends WatchedQuery<ResultType> = WatchedQuery<ResultType>>(query: Query) => Query["state"];
@@ -0,0 +1,56 @@
1
+ import React from 'react';
2
+ import { createSuspendingPromise, useTemporaryHold } from './suspense-utils';
3
+ /**
4
+ * A hook to access and subscribe to the results of an existing {@link WatchedQuery}.
5
+ * @example
6
+ * export const ContentComponent = () => {
7
+ * const { data: lists } = useWatchedQuerySuspenseSubscription(listsQuery);
8
+ *
9
+ * return <View>
10
+ * {lists.map((l) => (
11
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
12
+ * ))}
13
+ * </View>;
14
+ * }
15
+ *
16
+ * export const DisplayComponent = () => {
17
+ * return (
18
+ * <Suspense fallback={<div>Loading content...</div>}>
19
+ * <ContentComponent />
20
+ * </Suspense>
21
+ * );
22
+ * }
23
+ */
24
+ export const useWatchedQuerySuspenseSubscription = (query) => {
25
+ const { releaseHold } = 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
+ // This runs on the first iteration before the component is suspended
38
+ // We should only release the hold once the component is no longer loading
39
+ if (!query.state.isLoading) {
40
+ releaseHold();
41
+ }
42
+ return dispose;
43
+ }, []);
44
+ if (query.state.error != null) {
45
+ // Report errors - this is caught by an error boundary
46
+ throw query.state.error;
47
+ }
48
+ else if (!query.state.isLoading) {
49
+ // Happy path data return
50
+ return query.state;
51
+ }
52
+ else {
53
+ // Notify suspense is required
54
+ throw createSuspendingPromise(query);
55
+ }
56
+ };
@@ -0,0 +1,6 @@
1
+ import { CompilableQuery } from '@powersync/common';
2
+ import { AdditionalOptions } from '../watched/watch-types';
3
+ /**
4
+ * @internal This is not exported in the index.ts
5
+ */
6
+ export declare const useWatchedSuspenseQuery: <T = any>(query: string | CompilableQuery<T>, parameters?: any[], options?: AdditionalOptions) => import("@powersync/common").WatchedQueryState<readonly Readonly<T>[]>;
@@ -0,0 +1,25 @@
1
+ import { generateQueryKey, getQueryStore } from '../../QueryStore';
2
+ import { usePowerSync } from '../PowerSyncContext';
3
+ import { constructCompatibleQuery } from '../watched/watch-utils';
4
+ import { useWatchedQuerySuspenseSubscription } from './useWatchedQuerySuspenseSubscription';
5
+ /**
6
+ * @internal This is not exported in the index.ts
7
+ */
8
+ export const useWatchedSuspenseQuery = (query, parameters = [], options = {}) => {
9
+ const powerSync = usePowerSync();
10
+ if (!powerSync) {
11
+ throw new Error('PowerSync not configured.');
12
+ }
13
+ // Note, we don't need to check if the query changed since we fetch the WatchedQuery
14
+ // from the store given these query params
15
+ const { parsedQuery } = constructCompatibleQuery(query, parameters, options);
16
+ const { sql: parsedSql, parameters: parsedParameters } = parsedQuery.compile();
17
+ const key = generateQueryKey(parsedSql, parsedParameters, options);
18
+ // When the component is suspended, all state is discarded. We don't get
19
+ // any notification of that. So checkoutQuery reserves a temporary hold
20
+ // on the query.
21
+ // Once the component "commits", we exchange that for a permanent hold.
22
+ const store = getQueryStore(powerSync);
23
+ const watchedQuery = store.getQuery(key, parsedQuery, options);
24
+ return useWatchedQuerySuspenseSubscription(watchedQuery);
25
+ };
@@ -1,4 +1,4 @@
1
- import { usePowerSyncStatus } from './usePowerSyncStatus';
1
+ import { usePowerSyncStatus } from './deprecated/usePowerSyncStatus';
2
2
  /**
3
3
  * Custom hook that provides access to the current status of PowerSync.
4
4
  * @returns The PowerSync Database status.
@@ -13,4 +13,4 @@ import { usePowerSyncStatus } from './usePowerSyncStatus';
13
13
  * </div>
14
14
  * };
15
15
  */
16
- export const useStatus = usePowerSyncStatus;
16
+ export const useStatus = () => usePowerSyncStatus();
@@ -0,0 +1,38 @@
1
+ import { type CompilableQuery } from '@powersync/common';
2
+ import { AdditionalOptions, DifferentialHookOptions, QueryResult, ReadonlyQueryResult } from './watch-types';
3
+ /**
4
+ * A hook to access the results of a watched query.
5
+ * @example
6
+ *
7
+ * export const Component = () => {
8
+ * // The lists array here will be a new Array reference whenever a change to the
9
+ * // lists table is made.
10
+ * const { data: lists } = useQuery('SELECT * from lists');
11
+ *
12
+ * return <View>
13
+ * {lists.map((l) => (
14
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
15
+ * ))}
16
+ * </View>
17
+ * }
18
+ *
19
+ * export const DiffComponent = () => {
20
+ * // A differential query will emit results when a change to the result set occurs.
21
+ * // The internal array object references are maintained for unchanged rows.
22
+ * // The returned lists array is read only when a `differentiator` is provided.
23
+ * const { data: lists } = useQuery('SELECT * from lists', [], {
24
+ * differentiator: {
25
+ * identify: (item) => item.id,
26
+ * compareBy: (item) => JSON.stringify(item)
27
+ * }
28
+ * });
29
+ *
30
+ * return <View>
31
+ * {lists.map((l) => (
32
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
33
+ * ))}
34
+ * </View>
35
+ * }
36
+ */
37
+ export declare function useQuery<RowType = any>(query: string | CompilableQuery<RowType>, parameters?: any[], options?: AdditionalOptions): QueryResult<RowType>;
38
+ export declare function useQuery<RowType = any>(query: string | CompilableQuery<RowType>, paramerers?: any[], options?: DifferentialHookOptions<RowType>): ReadonlyQueryResult<RowType>;