@powersync/react 0.0.0-dev-20250722092404 → 0.0.0-dev-20250728083821

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 +1 -121
  2. package/lib/QueryStore.d.ts +6 -5
  3. package/lib/QueryStore.js +6 -32
  4. package/lib/WatchedQuery.d.ts +36 -0
  5. package/lib/WatchedQuery.js +148 -0
  6. package/lib/hooks/{deprecated/usePowerSyncQuery.js → usePowerSyncQuery.js} +1 -1
  7. package/lib/hooks/{deprecated/usePowerSyncStatus.js → usePowerSyncStatus.js} +1 -1
  8. package/lib/hooks/{deprecated/usePowerSyncWatchedQuery.js → usePowerSyncWatchedQuery.js} +1 -1
  9. package/lib/hooks/useQuery.d.ts +34 -0
  10. package/lib/hooks/useQuery.js +126 -0
  11. package/lib/hooks/useStatus.js +2 -2
  12. package/lib/hooks/useSuspenseQuery.d.ts +25 -0
  13. package/lib/hooks/useSuspenseQuery.js +74 -0
  14. package/lib/index.d.ts +5 -9
  15. package/lib/index.js +5 -7
  16. package/package.json +3 -6
  17. package/lib/hooks/suspense/SuspenseQueryResult.d.ts +0 -3
  18. package/lib/hooks/suspense/SuspenseQueryResult.js +0 -1
  19. package/lib/hooks/suspense/suspense-utils.d.ts +0 -19
  20. package/lib/hooks/suspense/suspense-utils.js +0 -78
  21. package/lib/hooks/suspense/useSingleSuspenseQuery.d.ts +0 -10
  22. package/lib/hooks/suspense/useSingleSuspenseQuery.js +0 -75
  23. package/lib/hooks/suspense/useSuspenseQuery.d.ts +0 -53
  24. package/lib/hooks/suspense/useSuspenseQuery.js +0 -10
  25. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.d.ts +0 -23
  26. package/lib/hooks/suspense/useWatchedQuerySuspenseSubscription.js +0 -56
  27. package/lib/hooks/suspense/useWatchedSuspenseQuery.d.ts +0 -6
  28. package/lib/hooks/suspense/useWatchedSuspenseQuery.js +0 -25
  29. package/lib/hooks/watched/useQuery.d.ts +0 -38
  30. package/lib/hooks/watched/useQuery.js +0 -32
  31. package/lib/hooks/watched/useSingleQuery.d.ts +0 -3
  32. package/lib/hooks/watched/useSingleQuery.js +0 -52
  33. package/lib/hooks/watched/useWatchedQuery.d.ts +0 -13
  34. package/lib/hooks/watched/useWatchedQuery.js +0 -43
  35. package/lib/hooks/watched/useWatchedQuerySubscription.d.ts +0 -16
  36. package/lib/hooks/watched/useWatchedQuerySubscription.js +0 -29
  37. package/lib/hooks/watched/watch-types.d.ts +0 -62
  38. package/lib/hooks/watched/watch-types.js +0 -1
  39. package/lib/hooks/watched/watch-utils.d.ts +0 -12
  40. package/lib/hooks/watched/watch-utils.js +0 -56
  41. /package/lib/hooks/{deprecated/usePowerSyncQuery.d.ts → usePowerSyncQuery.d.ts} +0 -0
  42. /package/lib/hooks/{deprecated/usePowerSyncStatus.d.ts → usePowerSyncStatus.d.ts} +0 -0
  43. /package/lib/hooks/{deprecated/usePowerSyncWatchedQuery.d.ts → 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 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.
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.
73
73
 
74
74
  ```JSX
75
75
  // TodoListDisplay.jsx
@@ -271,123 +271,3 @@ 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
- comparator: {
350
- keyBy: (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
- comparator: {
378
- keyBy: (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,10 +1,11 @@
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;
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;
4
5
  export declare class QueryStore {
5
6
  private db;
6
- cache: Map<string, WatchedQuery<unknown, import("@powersync/common").WatchedQueryOptions, import("@powersync/common").WatchedQueryListener<unknown>>>;
7
+ cache: Map<string, WatchedQuery>;
7
8
  constructor(db: AbstractPowerSyncDatabase);
8
- getQuery<RowType>(key: string, query: WatchCompatibleQuery<RowType[]>, options: DifferentialHookOptions<RowType>): import("@powersync/common").DifferentialWatchedQuery<RowType>;
9
+ getQuery(key: string, query: Query<unknown>, options: AdditionalOptions): WatchedQuery;
9
10
  }
10
11
  export declare function getQueryStore(db: AbstractPowerSyncDatabase): QueryStore;
package/lib/QueryStore.js CHANGED
@@ -1,4 +1,4 @@
1
- import { WatchedQueryListenerEvent } from '@powersync/common';
1
+ import { WatchedQuery } from './WatchedQuery';
2
2
  export function generateQueryKey(sqlStatement, parameters, options) {
3
3
  return `${sqlStatement} -- ${JSON.stringify(parameters)} -- ${JSON.stringify(options)}`;
4
4
  }
@@ -12,41 +12,15 @@ export class QueryStore {
12
12
  if (this.cache.has(key)) {
13
13
  return this.cache.get(key);
14
14
  }
15
- const watch = options.comparator
16
- ? this.db.customQuery(query).differentialWatch({
17
- comparator: options.comparator,
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: () => {
15
+ const q = new WatchedQuery(this.db, query, options);
16
+ const disposer = q.registerListener({
17
+ disposed: () => {
28
18
  this.cache.delete(key);
29
19
  disposer?.();
30
20
  }
31
21
  });
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;
22
+ this.cache.set(key, q);
23
+ return q;
50
24
  }
51
25
  }
52
26
  let queryStores = undefined;
@@ -0,0 +1,36 @@
1
+ import { AbstractPowerSyncDatabase, BaseListener, BaseObserver, CompilableQuery, Disposable } from '@powersync/common';
2
+ import { AdditionalOptions } from './hooks/useQuery';
3
+ export declare class Query<T> {
4
+ rawQuery: string | CompilableQuery<T>;
5
+ sqlStatement: string;
6
+ queryParameters: any[];
7
+ }
8
+ export interface WatchedQueryListener extends BaseListener {
9
+ onUpdate: () => void;
10
+ disposed: () => void;
11
+ }
12
+ export declare class WatchedQuery extends BaseObserver<WatchedQueryListener> implements Disposable {
13
+ readyPromise: Promise<void>;
14
+ isReady: boolean;
15
+ currentData: any[] | undefined;
16
+ currentError: any;
17
+ tables: any[] | undefined;
18
+ private temporaryHolds;
19
+ private controller;
20
+ private db;
21
+ private resolveReady;
22
+ readonly query: Query<unknown>;
23
+ readonly options: AdditionalOptions;
24
+ constructor(db: AbstractPowerSyncDatabase, query: Query<unknown>, options: AdditionalOptions);
25
+ get logger(): import("js-logger").ILogger | Console;
26
+ addTemporaryHold(): () => void;
27
+ registerListener(listener: Partial<WatchedQueryListener>): () => void;
28
+ private fetchTables;
29
+ fetchData(): Promise<void>;
30
+ private maybeListen;
31
+ private setData;
32
+ private setError;
33
+ private onUpdateListenersCount;
34
+ private maybeDispose;
35
+ dispose(): Promise<void>;
36
+ }
@@ -0,0 +1,148 @@
1
+ import { BaseObserver, runOnSchemaChange } from '@powersync/common';
2
+ export class Query {
3
+ rawQuery;
4
+ sqlStatement;
5
+ queryParameters;
6
+ }
7
+ export class WatchedQuery extends BaseObserver {
8
+ readyPromise;
9
+ isReady = false;
10
+ currentData;
11
+ currentError;
12
+ tables;
13
+ temporaryHolds = new Set();
14
+ controller;
15
+ db;
16
+ resolveReady;
17
+ query;
18
+ options;
19
+ constructor(db, query, options) {
20
+ super();
21
+ this.db = db;
22
+ this.query = query;
23
+ this.options = options;
24
+ this.readyPromise = new Promise((resolve) => {
25
+ this.resolveReady = resolve;
26
+ });
27
+ }
28
+ get logger() {
29
+ return this.db.logger ?? console;
30
+ }
31
+ addTemporaryHold() {
32
+ const ref = new Object();
33
+ this.temporaryHolds.add(ref);
34
+ this.maybeListen();
35
+ let timeout;
36
+ const release = () => {
37
+ this.temporaryHolds.delete(ref);
38
+ if (timeout) {
39
+ clearTimeout(timeout);
40
+ }
41
+ this.maybeDispose();
42
+ };
43
+ const timeoutRelease = () => {
44
+ if (this.isReady || this.controller == null) {
45
+ release();
46
+ }
47
+ else {
48
+ // If the query is taking long, keep the temporary hold.
49
+ timeout = setTimeout(timeoutRelease, 5_000);
50
+ }
51
+ };
52
+ timeout = setTimeout(timeoutRelease, 5_000);
53
+ return release;
54
+ }
55
+ registerListener(listener) {
56
+ const disposer = super.registerListener(listener);
57
+ this.maybeListen();
58
+ return () => {
59
+ disposer();
60
+ this.maybeDispose();
61
+ };
62
+ }
63
+ async fetchTables() {
64
+ try {
65
+ this.tables = await this.db.resolveTables(this.query.sqlStatement, this.query.queryParameters, this.options);
66
+ }
67
+ catch (e) {
68
+ this.logger.error('Failed to fetch tables:', e);
69
+ this.setError(e);
70
+ }
71
+ }
72
+ async fetchData() {
73
+ try {
74
+ const result = typeof this.query.rawQuery == 'string'
75
+ ? await this.db.getAll(this.query.sqlStatement, this.query.queryParameters)
76
+ : await this.query.rawQuery.execute();
77
+ const data = result ?? [];
78
+ this.setData(data);
79
+ }
80
+ catch (e) {
81
+ this.logger.error('Failed to fetch data:', e);
82
+ this.setError(e);
83
+ }
84
+ }
85
+ maybeListen() {
86
+ if (this.controller != null) {
87
+ return;
88
+ }
89
+ if (this.onUpdateListenersCount() == 0 && this.temporaryHolds.size == 0) {
90
+ return;
91
+ }
92
+ const controller = new AbortController();
93
+ this.controller = controller;
94
+ const onError = (error) => {
95
+ this.setError(error);
96
+ };
97
+ const watchQuery = async (abortSignal) => {
98
+ await this.fetchTables();
99
+ await this.fetchData();
100
+ if (!this.options.runQueryOnce) {
101
+ this.db.onChangeWithCallback({
102
+ onChange: async () => {
103
+ await this.fetchData();
104
+ },
105
+ onError
106
+ }, {
107
+ ...this.options,
108
+ signal: abortSignal,
109
+ tables: this.tables
110
+ });
111
+ }
112
+ };
113
+ runOnSchemaChange(watchQuery, this.db, { signal: this.controller.signal });
114
+ }
115
+ setData(results) {
116
+ this.isReady = true;
117
+ this.currentData = results;
118
+ this.currentError = undefined;
119
+ this.resolveReady?.();
120
+ this.iterateListeners((l) => l.onUpdate?.());
121
+ }
122
+ setError(error) {
123
+ this.isReady = true;
124
+ this.currentData = undefined;
125
+ this.currentError = error;
126
+ this.resolveReady?.();
127
+ this.iterateListeners((l) => l.onUpdate?.());
128
+ }
129
+ onUpdateListenersCount() {
130
+ return Array.from(this.listeners).filter((listener) => listener.onUpdate !== undefined).length;
131
+ }
132
+ maybeDispose() {
133
+ if (this.onUpdateListenersCount() == 0 && this.temporaryHolds.size == 0) {
134
+ this.controller?.abort();
135
+ this.controller = undefined;
136
+ this.isReady = false;
137
+ this.currentData = undefined;
138
+ this.currentError = undefined;
139
+ this.dispose();
140
+ this.readyPromise = new Promise((resolve, reject) => {
141
+ this.resolveReady = resolve;
142
+ });
143
+ }
144
+ }
145
+ async dispose() {
146
+ this.iterateAsyncListeners(async (l) => l.disposed?.());
147
+ }
148
+ }
@@ -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,34 @@
1
+ import { type CompilableQuery, type SQLWatchOptions } from '@powersync/common';
2
+ export interface AdditionalOptions extends Omit<SQLWatchOptions, 'signal'> {
3
+ runQueryOnce?: boolean;
4
+ }
5
+ export type QueryResult<T> = {
6
+ data: T[];
7
+ /**
8
+ * Indicates the initial loading state (hard loading). Loading becomes false once the first set of results from the watched query is available or an error occurs.
9
+ */
10
+ isLoading: boolean;
11
+ /**
12
+ * Indicates whether the query is currently fetching data, is true during the initial load and any time when the query is re-evaluating (useful for large queries).
13
+ */
14
+ isFetching: boolean;
15
+ error: Error | undefined;
16
+ /**
17
+ * Function used to run the query again.
18
+ */
19
+ refresh?: (signal?: AbortSignal) => Promise<void>;
20
+ };
21
+ /**
22
+ * A hook to access the results of a watched query.
23
+ * @example
24
+ * export const Component = () => {
25
+ * const { data: lists } = useQuery('SELECT * from lists');
26
+ *
27
+ * return <View>
28
+ * {lists.map((l) => (
29
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
30
+ * ))}
31
+ * </View>
32
+ * }
33
+ */
34
+ export declare const useQuery: <T = any>(query: string | CompilableQuery<T>, parameters?: any[], options?: AdditionalOptions) => QueryResult<T>;
@@ -0,0 +1,126 @@
1
+ import { parseQuery } from '@powersync/common';
2
+ import React from 'react';
3
+ import { usePowerSync } from './PowerSyncContext';
4
+ /**
5
+ * A hook to access the results of a watched query.
6
+ * @example
7
+ * export const Component = () => {
8
+ * const { data: lists } = useQuery('SELECT * from lists');
9
+ *
10
+ * return <View>
11
+ * {lists.map((l) => (
12
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
13
+ * ))}
14
+ * </View>
15
+ * }
16
+ */
17
+ export const useQuery = (query, parameters = [], options = { runQueryOnce: false }) => {
18
+ const powerSync = usePowerSync();
19
+ const logger = powerSync?.logger ?? console;
20
+ if (!powerSync) {
21
+ return { isLoading: false, isFetching: false, data: [], error: new Error('PowerSync not configured.') };
22
+ }
23
+ let parsedQuery;
24
+ try {
25
+ parsedQuery = parseQuery(query, parameters);
26
+ }
27
+ catch (error) {
28
+ logger.error('Failed to parse query:', error);
29
+ return { isLoading: false, isFetching: false, data: [], error };
30
+ }
31
+ const { sqlStatement, parameters: queryParameters } = parsedQuery;
32
+ const [data, setData] = React.useState([]);
33
+ const [error, setError] = React.useState(undefined);
34
+ const [isLoading, setIsLoading] = React.useState(true);
35
+ const [isFetching, setIsFetching] = React.useState(true);
36
+ const [tables, setTables] = React.useState([]);
37
+ const memoizedParams = React.useMemo(() => queryParameters, [JSON.stringify(queryParameters)]);
38
+ const memoizedOptions = React.useMemo(() => options, [JSON.stringify(options)]);
39
+ const abortController = React.useRef(new AbortController());
40
+ const previousQueryRef = React.useRef({ sqlStatement, memoizedParams });
41
+ // Indicates that the query will be re-fetched due to a change in the query.
42
+ // Used when `isFetching` hasn't been set to true yet due to React execution.
43
+ const shouldFetch = React.useMemo(() => previousQueryRef.current.sqlStatement !== sqlStatement ||
44
+ JSON.stringify(previousQueryRef.current.memoizedParams) != JSON.stringify(memoizedParams), [powerSync, sqlStatement, memoizedParams, isFetching]);
45
+ const handleResult = (result) => {
46
+ previousQueryRef.current = { sqlStatement, memoizedParams };
47
+ setData(result);
48
+ setIsLoading(false);
49
+ setIsFetching(false);
50
+ setError(undefined);
51
+ };
52
+ const handleError = (e) => {
53
+ previousQueryRef.current = { sqlStatement, memoizedParams };
54
+ setData([]);
55
+ setIsLoading(false);
56
+ setIsFetching(false);
57
+ const wrappedError = new Error('PowerSync failed to fetch data: ' + e.message);
58
+ wrappedError.cause = e;
59
+ setError(wrappedError);
60
+ };
61
+ const fetchData = async (signal) => {
62
+ setIsFetching(true);
63
+ try {
64
+ const result = typeof query == 'string' ? await powerSync.getAll(sqlStatement, queryParameters) : await query.execute();
65
+ if (signal?.aborted) {
66
+ return;
67
+ }
68
+ handleResult(result);
69
+ }
70
+ catch (e) {
71
+ logger.error('Failed to fetch data:', e);
72
+ handleError(e);
73
+ }
74
+ };
75
+ const fetchTables = async (signal) => {
76
+ try {
77
+ const tables = await powerSync.resolveTables(sqlStatement, memoizedParams, memoizedOptions);
78
+ if (signal?.aborted) {
79
+ return;
80
+ }
81
+ setTables(tables);
82
+ }
83
+ catch (e) {
84
+ logger.error('Failed to fetch tables:', e);
85
+ handleError(e);
86
+ }
87
+ };
88
+ React.useEffect(() => {
89
+ const abortController = new AbortController();
90
+ const updateData = async () => {
91
+ await fetchTables(abortController.signal);
92
+ await fetchData(abortController.signal);
93
+ };
94
+ updateData();
95
+ const l = powerSync.registerListener({
96
+ schemaChanged: updateData
97
+ });
98
+ return () => {
99
+ abortController.abort();
100
+ l?.();
101
+ };
102
+ }, [powerSync, memoizedParams, sqlStatement]);
103
+ React.useEffect(() => {
104
+ // Abort any previous watches
105
+ abortController.current?.abort();
106
+ abortController.current = new AbortController();
107
+ if (!options.runQueryOnce) {
108
+ powerSync.onChangeWithCallback({
109
+ onChange: async () => {
110
+ await fetchData(abortController.current.signal);
111
+ },
112
+ onError(e) {
113
+ handleError(e);
114
+ }
115
+ }, {
116
+ ...options,
117
+ signal: abortController.current.signal,
118
+ tables
119
+ });
120
+ }
121
+ return () => {
122
+ abortController.current?.abort();
123
+ };
124
+ }, [powerSync, sqlStatement, memoizedParams, memoizedOptions, tables]);
125
+ return { isLoading, isFetching: isFetching || shouldFetch, data, error, refresh: fetchData };
126
+ };
@@ -1,4 +1,4 @@
1
- import { usePowerSyncStatus } from './deprecated/usePowerSyncStatus';
1
+ import { usePowerSyncStatus } from './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 './deprecated/usePowerSyncStatus';
13
13
  * </div>
14
14
  * };
15
15
  */
16
- export const useStatus = () => usePowerSyncStatus();
16
+ export const useStatus = usePowerSyncStatus;
@@ -0,0 +1,25 @@
1
+ import { CompilableQuery } from '@powersync/common';
2
+ import { AdditionalOptions, QueryResult } from './useQuery';
3
+ export type SuspenseQueryResult<T> = Pick<QueryResult<T>, 'data' | 'refresh'>;
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
+ * const { data: lists } = useSuspenseQuery('SELECT * from lists');
9
+ *
10
+ * return <View>
11
+ * {lists.map((l) => (
12
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
13
+ * ))}
14
+ * </View>;
15
+ * }
16
+ *
17
+ * export const DisplayComponent = () => {
18
+ * return (
19
+ * <Suspense fallback={<div>Loading content...</div>}>
20
+ * <ContentComponent />
21
+ * </Suspense>
22
+ * );
23
+ * }
24
+ */
25
+ export declare const useSuspenseQuery: <T = any>(query: string | CompilableQuery<T>, parameters?: any[], options?: AdditionalOptions) => SuspenseQueryResult<T>;