@powersync/react 1.4.4 → 1.5.0
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.
- package/README.md +161 -6
- package/lib/QueryStore.d.ts +11 -0
- package/lib/QueryStore.js +36 -0
- package/lib/WatchedQuery.d.ts +35 -0
- package/lib/WatchedQuery.js +144 -0
- package/lib/hooks/useQuery.js +10 -3
- package/lib/hooks/useSuspenseQuery.d.ts +25 -0
- package/lib/hooks/useSuspenseQuery.js +74 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1 -0
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
|
-
# React
|
|
1
|
+
# React Hooks for PowerSync
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `powersync/react` package provides React hooks for use with the JavaScript Web SDK or React Native SDK. These hooks are designed to support reactivity, and can be used to automatically re-render React components when query results update or to access PowerSync connectivity status changes.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
### Context
|
|
4
8
|
|
|
5
9
|
Configure a PowerSync DB connection and add it to a context provider.
|
|
6
10
|
|
|
@@ -44,7 +48,7 @@ export const TodoListDisplay = () => {
|
|
|
44
48
|
}
|
|
45
49
|
```
|
|
46
50
|
|
|
47
|
-
|
|
51
|
+
## Accessing PowerSync Status
|
|
48
52
|
|
|
49
53
|
The provided PowerSync client status is available with the `useStatus` hook.
|
|
50
54
|
|
|
@@ -63,9 +67,9 @@ const Component = () => {
|
|
|
63
67
|
};
|
|
64
68
|
```
|
|
65
69
|
|
|
66
|
-
|
|
70
|
+
## Reactive Queries
|
|
67
71
|
|
|
68
|
-
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 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.
|
|
69
73
|
|
|
70
74
|
```JSX
|
|
71
75
|
// TodoListDisplay.jsx
|
|
@@ -82,7 +86,7 @@ export const TodoListDisplay = () => {
|
|
|
82
86
|
}
|
|
83
87
|
```
|
|
84
88
|
|
|
85
|
-
|
|
89
|
+
### Query Loading
|
|
86
90
|
|
|
87
91
|
The response from `useQuery` includes the `isLoading` and `isFetching` properties, which indicate the current state of data retrieval. This can be used to show loading spinners or conditional widgets.
|
|
88
92
|
|
|
@@ -116,3 +120,154 @@ export const TodoListsDisplayDemo = () => {
|
|
|
116
120
|
};
|
|
117
121
|
|
|
118
122
|
```
|
|
123
|
+
|
|
124
|
+
### Suspense
|
|
125
|
+
|
|
126
|
+
The `useSuspenseQuery` hook also allows you to access the results of a watched query, but its loading and fetching states are handled through [Suspense](https://react.dev/reference/react/Suspense). Unlike `useQuery`, the hook doesn't return `isLoading` or `isFetching` for the loading states nor `error` for the error state. These should be handled with variants of `<Suspense>` and `<ErrorBoundary>` respectively.
|
|
127
|
+
|
|
128
|
+
```JSX
|
|
129
|
+
// TodoListDisplaySuspense.jsx
|
|
130
|
+
import { ErrorBoundary } from 'react-error-boundary';
|
|
131
|
+
import { Suspense } from 'react';
|
|
132
|
+
import { useSuspenseQuery } from '@powersync/react';
|
|
133
|
+
|
|
134
|
+
const TodoListContent = () => {
|
|
135
|
+
const { data: todoLists } = useSuspenseQuery("SELECT * FROM lists");
|
|
136
|
+
|
|
137
|
+
return (
|
|
138
|
+
<ul>
|
|
139
|
+
{todoLists.map((list) => (
|
|
140
|
+
<li key={list.id}>{list.name}</li>
|
|
141
|
+
))}
|
|
142
|
+
</ul>
|
|
143
|
+
);
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
export const TodoListDisplaySuspense = () => {
|
|
148
|
+
return (
|
|
149
|
+
<ErrorBoundary fallback={<div>Something went wrong</div>}>
|
|
150
|
+
<Suspense fallback={<div>Loading todo lists...</div>}>
|
|
151
|
+
<TodoListContent />
|
|
152
|
+
</Suspense>
|
|
153
|
+
</ErrorBoundary>
|
|
154
|
+
);
|
|
155
|
+
};
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
#### Blocking navigation on Suspense
|
|
159
|
+
|
|
160
|
+
When you provide a Suspense fallback, suspending components will cause the fallback to render. Alternatively, React's [startTransition](https://react.dev/reference/react/startTransition) allows navigation to be blocked until the suspending components have completed, preventing the fallback from displaying. This behavior can be facilitated by your router — for example, react-router supports this with its [startTransition flag](https://reactrouter.com/en/main/upgrading/future#v7_starttransition).
|
|
161
|
+
|
|
162
|
+
> Note: In this example, the `<Suspense>` boundary is intentionally omitted to delegate the handling of the suspending state to the router.
|
|
163
|
+
|
|
164
|
+
```JSX
|
|
165
|
+
// routerAndLists.jsx
|
|
166
|
+
import { RouterProvider } from 'react-router-dom';
|
|
167
|
+
import { ErrorBoundary } from 'react-error-boundary';
|
|
168
|
+
import { useSuspenseQuery } from '@powersync/react';
|
|
169
|
+
|
|
170
|
+
export const Index() {
|
|
171
|
+
return <RouterProvider router={router} future={{v7_startTransition: true}} />
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const TodoListContent = () => {
|
|
175
|
+
const { data: todoLists } = useSuspenseQuery("SELECT * FROM lists");
|
|
176
|
+
|
|
177
|
+
return (
|
|
178
|
+
<ul>
|
|
179
|
+
{todoLists.map((list) => (
|
|
180
|
+
<li key={list.id}>{list.name}</li>
|
|
181
|
+
))}
|
|
182
|
+
</ul>
|
|
183
|
+
);
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
export const TodoListsPage = () => {
|
|
188
|
+
return (
|
|
189
|
+
<ErrorBoundary fallback={<div>Something went wrong</div>}>
|
|
190
|
+
<TodoListContent />
|
|
191
|
+
</ErrorBoundary>
|
|
192
|
+
);
|
|
193
|
+
};
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
#### Managing Suspense When Updating `useSuspenseQuery` Parameters
|
|
197
|
+
|
|
198
|
+
When data in dependent tables changes, `useSuspenseQuery` automatically updates without suspending. However, changing the query parameters causes the hook to restart and enter a suspending state again, which triggers the suspense fallback. To prevent this and keep displaying the stale data until the new data is loaded, wrap the parameter changes in React's [startTransition](https://react.dev/reference/react/startTransition) or use [useDeferredValue](https://react.dev/reference/react/useDeferredValue).
|
|
199
|
+
|
|
200
|
+
```JSX
|
|
201
|
+
// TodoListDisplaySuspenseTransition.jsx
|
|
202
|
+
import { ErrorBoundary } from 'react-error-boundary';
|
|
203
|
+
import React, { Suspense } from 'react';
|
|
204
|
+
import { useSuspenseQuery } from '@powersync/react';
|
|
205
|
+
|
|
206
|
+
const TodoListContent = () => {
|
|
207
|
+
const [query, setQuery] = React.useState('SELECT * FROM lists');
|
|
208
|
+
const { data: todoLists } = useSuspenseQuery(query);
|
|
209
|
+
|
|
210
|
+
return (
|
|
211
|
+
<div>
|
|
212
|
+
<button
|
|
213
|
+
onClick={() => {
|
|
214
|
+
React.startTransition(() => setQuery('SELECT * from lists limit 1'));
|
|
215
|
+
}}>
|
|
216
|
+
Update
|
|
217
|
+
</button>
|
|
218
|
+
<ul>
|
|
219
|
+
{todoLists.map((list) => (
|
|
220
|
+
<li key={list.id}>{list.name}</li>
|
|
221
|
+
))}
|
|
222
|
+
</ul>
|
|
223
|
+
</div>
|
|
224
|
+
);
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
export const TodoListDisplaySuspense = () => {
|
|
228
|
+
return (
|
|
229
|
+
<ErrorBoundary fallback={<div>Something went wrong</div>}>
|
|
230
|
+
<Suspense fallback={<div>Loading todo lists...</div>}>
|
|
231
|
+
<TodoListContent />
|
|
232
|
+
</Suspense>
|
|
233
|
+
</ErrorBoundary>
|
|
234
|
+
);
|
|
235
|
+
};
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
and
|
|
239
|
+
|
|
240
|
+
```JSX
|
|
241
|
+
// TodoListDisplaySuspenseDeferred.jsx
|
|
242
|
+
import { ErrorBoundary } from 'react-error-boundary';
|
|
243
|
+
import React, { Suspense } from 'react';
|
|
244
|
+
import { useSuspenseQuery } from '@powersync/react';
|
|
245
|
+
|
|
246
|
+
const TodoListContent = () => {
|
|
247
|
+
const [query, setQuery] = React.useState('SELECT * FROM lists');
|
|
248
|
+
const deferredQueryQuery = React.useDeferredValue(query);
|
|
249
|
+
|
|
250
|
+
const { data: todoLists } = useSuspenseQuery(deferredQueryQuery);
|
|
251
|
+
|
|
252
|
+
return (
|
|
253
|
+
<div>
|
|
254
|
+
<button onClick={() => setQuery('SELECT * from lists limit 1')}>Update</button>
|
|
255
|
+
<ul>
|
|
256
|
+
{todoLists.map((list) => (
|
|
257
|
+
<li key={list.id}>{list.name}</li>
|
|
258
|
+
))}
|
|
259
|
+
</ul>
|
|
260
|
+
</div>
|
|
261
|
+
);
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
export const TodoListDisplaySuspense = () => {
|
|
265
|
+
return (
|
|
266
|
+
<ErrorBoundary fallback={<div>Something went wrong</div>}>
|
|
267
|
+
<Suspense fallback={<div>Loading todo lists...</div>}>
|
|
268
|
+
<TodoListContent />
|
|
269
|
+
</Suspense>
|
|
270
|
+
</ErrorBoundary>
|
|
271
|
+
);
|
|
272
|
+
};
|
|
273
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
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;
|
|
5
|
+
export declare class QueryStore {
|
|
6
|
+
private db;
|
|
7
|
+
cache: Map<string, WatchedQuery>;
|
|
8
|
+
constructor(db: AbstractPowerSyncDatabase);
|
|
9
|
+
getQuery(key: string, query: Query<unknown>, options: AdditionalOptions): WatchedQuery;
|
|
10
|
+
}
|
|
11
|
+
export declare function getQueryStore(db: AbstractPowerSyncDatabase): QueryStore;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { WatchedQuery } from './WatchedQuery';
|
|
2
|
+
export function generateQueryKey(sqlStatement, parameters, options) {
|
|
3
|
+
return `${sqlStatement} -- ${JSON.stringify(parameters)} -- ${JSON.stringify(options)}`;
|
|
4
|
+
}
|
|
5
|
+
export class QueryStore {
|
|
6
|
+
db;
|
|
7
|
+
cache = new Map();
|
|
8
|
+
constructor(db) {
|
|
9
|
+
this.db = db;
|
|
10
|
+
}
|
|
11
|
+
getQuery(key, query, options) {
|
|
12
|
+
if (this.cache.has(key)) {
|
|
13
|
+
return this.cache.get(key);
|
|
14
|
+
}
|
|
15
|
+
const q = new WatchedQuery(this.db, query, options);
|
|
16
|
+
const disposer = q.registerListener({
|
|
17
|
+
disposed: () => {
|
|
18
|
+
this.cache.delete(key);
|
|
19
|
+
disposer?.();
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
this.cache.set(key, q);
|
|
23
|
+
return q;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
let queryStores = undefined;
|
|
27
|
+
export function getQueryStore(db) {
|
|
28
|
+
queryStores ||= new WeakMap();
|
|
29
|
+
const existing = queryStores.get(db);
|
|
30
|
+
if (existing) {
|
|
31
|
+
return existing;
|
|
32
|
+
}
|
|
33
|
+
const store = new QueryStore(db);
|
|
34
|
+
queryStores.set(db, store);
|
|
35
|
+
return store;
|
|
36
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
addTemporaryHold(): () => void;
|
|
26
|
+
registerListener(listener: Partial<WatchedQueryListener>): () => void;
|
|
27
|
+
private fetchTables;
|
|
28
|
+
fetchData(): Promise<void>;
|
|
29
|
+
private maybeListen;
|
|
30
|
+
private setData;
|
|
31
|
+
private setError;
|
|
32
|
+
private onUpdateListenersCount;
|
|
33
|
+
private maybeDispose;
|
|
34
|
+
dispose(): Promise<void>;
|
|
35
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { BaseObserver } 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
|
+
addTemporaryHold() {
|
|
29
|
+
const ref = new Object();
|
|
30
|
+
this.temporaryHolds.add(ref);
|
|
31
|
+
this.maybeListen();
|
|
32
|
+
let timeout;
|
|
33
|
+
const release = () => {
|
|
34
|
+
this.temporaryHolds.delete(ref);
|
|
35
|
+
if (timeout) {
|
|
36
|
+
clearTimeout(timeout);
|
|
37
|
+
}
|
|
38
|
+
this.maybeDispose();
|
|
39
|
+
};
|
|
40
|
+
const timeoutRelease = () => {
|
|
41
|
+
if (this.isReady || this.controller == null) {
|
|
42
|
+
release();
|
|
43
|
+
}
|
|
44
|
+
else {
|
|
45
|
+
// If the query is taking long, keep the temporary hold.
|
|
46
|
+
timeout = setTimeout(timeoutRelease, 5_000);
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
timeout = setTimeout(timeoutRelease, 5_000);
|
|
50
|
+
return release;
|
|
51
|
+
}
|
|
52
|
+
registerListener(listener) {
|
|
53
|
+
const disposer = super.registerListener(listener);
|
|
54
|
+
this.maybeListen();
|
|
55
|
+
return () => {
|
|
56
|
+
disposer();
|
|
57
|
+
this.maybeDispose();
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
async fetchTables() {
|
|
61
|
+
try {
|
|
62
|
+
this.tables = await this.db.resolveTables(this.query.sqlStatement, this.query.queryParameters, this.options);
|
|
63
|
+
}
|
|
64
|
+
catch (e) {
|
|
65
|
+
console.error('Failed to fetch tables:', e);
|
|
66
|
+
this.setError(e);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async fetchData() {
|
|
70
|
+
try {
|
|
71
|
+
const result = typeof this.query.rawQuery == 'string'
|
|
72
|
+
? await this.db.getAll(this.query.sqlStatement, this.query.queryParameters)
|
|
73
|
+
: await this.query.rawQuery.execute();
|
|
74
|
+
const data = result ?? [];
|
|
75
|
+
this.setData(data);
|
|
76
|
+
}
|
|
77
|
+
catch (e) {
|
|
78
|
+
console.error('Failed to fetch data:', e);
|
|
79
|
+
this.setError(e);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
maybeListen() {
|
|
83
|
+
if (this.controller != null) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (this.onUpdateListenersCount() == 0 && this.temporaryHolds.size == 0) {
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const controller = new AbortController();
|
|
90
|
+
this.controller = controller;
|
|
91
|
+
const onError = (error) => {
|
|
92
|
+
this.setError(error);
|
|
93
|
+
};
|
|
94
|
+
(async () => {
|
|
95
|
+
await this.fetchTables();
|
|
96
|
+
await this.fetchData();
|
|
97
|
+
if (!this.options.runQueryOnce) {
|
|
98
|
+
this.db.onChangeWithCallback({
|
|
99
|
+
onChange: async () => {
|
|
100
|
+
await this.fetchData();
|
|
101
|
+
},
|
|
102
|
+
onError
|
|
103
|
+
}, {
|
|
104
|
+
...this.options,
|
|
105
|
+
signal: this.controller.signal,
|
|
106
|
+
tables: this.tables
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
})();
|
|
110
|
+
}
|
|
111
|
+
setData(results) {
|
|
112
|
+
this.isReady = true;
|
|
113
|
+
this.currentData = results;
|
|
114
|
+
this.currentError = undefined;
|
|
115
|
+
this.resolveReady?.();
|
|
116
|
+
this.iterateListeners((l) => l.onUpdate?.());
|
|
117
|
+
}
|
|
118
|
+
setError(error) {
|
|
119
|
+
this.isReady = true;
|
|
120
|
+
this.currentData = undefined;
|
|
121
|
+
this.currentError = error;
|
|
122
|
+
this.resolveReady?.();
|
|
123
|
+
this.iterateListeners((l) => l.onUpdate?.());
|
|
124
|
+
}
|
|
125
|
+
onUpdateListenersCount() {
|
|
126
|
+
return Array.from(this.listeners).filter((listener) => listener.onUpdate !== undefined).length;
|
|
127
|
+
}
|
|
128
|
+
maybeDispose() {
|
|
129
|
+
if (this.onUpdateListenersCount() == 0 && this.temporaryHolds.size == 0) {
|
|
130
|
+
this.controller?.abort();
|
|
131
|
+
this.controller = undefined;
|
|
132
|
+
this.isReady = false;
|
|
133
|
+
this.currentData = undefined;
|
|
134
|
+
this.currentError = undefined;
|
|
135
|
+
this.dispose();
|
|
136
|
+
this.readyPromise = new Promise((resolve, reject) => {
|
|
137
|
+
this.resolveReady = resolve;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async dispose() {
|
|
142
|
+
this.iterateAsyncListeners(async (l) => l.disposed?.());
|
|
143
|
+
}
|
|
144
|
+
}
|
package/lib/hooks/useQuery.js
CHANGED
|
@@ -36,16 +36,23 @@ export const useQuery = (query, parameters = [], options = { runQueryOnce: false
|
|
|
36
36
|
const memoizedParams = React.useMemo(() => queryParameters, [JSON.stringify(queryParameters)]);
|
|
37
37
|
const memoizedOptions = React.useMemo(() => options, [JSON.stringify(options)]);
|
|
38
38
|
const abortController = React.useRef(new AbortController());
|
|
39
|
+
const previousQueryRef = React.useRef({ sqlStatement, memoizedParams });
|
|
40
|
+
// Indicates that the query will be re-fetched due to a change in the query.
|
|
41
|
+
// Used when `isFetching` hasn't been set to true yet due to React execution.
|
|
42
|
+
const shouldFetch = React.useMemo(() => previousQueryRef.current.sqlStatement !== sqlStatement ||
|
|
43
|
+
JSON.stringify(previousQueryRef.current.memoizedParams) != JSON.stringify(memoizedParams), [powerSync, sqlStatement, memoizedParams, isFetching]);
|
|
39
44
|
const handleResult = (result) => {
|
|
45
|
+
previousQueryRef.current = { sqlStatement, memoizedParams };
|
|
46
|
+
setData(result);
|
|
40
47
|
setIsLoading(false);
|
|
41
48
|
setIsFetching(false);
|
|
42
|
-
setData(result);
|
|
43
49
|
setError(undefined);
|
|
44
50
|
};
|
|
45
51
|
const handleError = (e) => {
|
|
52
|
+
previousQueryRef.current = { sqlStatement, memoizedParams };
|
|
53
|
+
setData([]);
|
|
46
54
|
setIsLoading(false);
|
|
47
55
|
setIsFetching(false);
|
|
48
|
-
setData([]);
|
|
49
56
|
const wrappedError = new Error('PowerSync failed to fetch data: ' + e.message);
|
|
50
57
|
wrappedError.cause = e;
|
|
51
58
|
setError(wrappedError);
|
|
@@ -99,5 +106,5 @@ export const useQuery = (query, parameters = [], options = { runQueryOnce: false
|
|
|
99
106
|
abortController.current?.abort();
|
|
100
107
|
};
|
|
101
108
|
}, [powerSync, sqlStatement, memoizedParams, memoizedOptions, tables]);
|
|
102
|
-
return { isLoading, isFetching, data, error, refresh: fetchData };
|
|
109
|
+
return { isLoading, isFetching: isFetching || shouldFetch, data, error, refresh: fetchData };
|
|
103
110
|
};
|
|
@@ -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>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
import { generateQueryKey, getQueryStore } from '../QueryStore';
|
|
3
|
+
import { usePowerSync } from './PowerSyncContext';
|
|
4
|
+
import { parseQuery } from '@powersync/common';
|
|
5
|
+
/**
|
|
6
|
+
* A hook to access the results of a watched query that suspends until the initial result has loaded.
|
|
7
|
+
* @example
|
|
8
|
+
* export const ContentComponent = () => {
|
|
9
|
+
* const { data: lists } = useSuspenseQuery('SELECT * from lists');
|
|
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 useSuspenseQuery = (query, parameters = [], options = {}) => {
|
|
27
|
+
const powerSync = usePowerSync();
|
|
28
|
+
if (!powerSync) {
|
|
29
|
+
throw new Error('PowerSync not configured.');
|
|
30
|
+
}
|
|
31
|
+
let parsedQuery;
|
|
32
|
+
try {
|
|
33
|
+
parsedQuery = parseQuery(query, parameters);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
throw new Error('Failed to parse query: ' + error.message);
|
|
37
|
+
}
|
|
38
|
+
const key = generateQueryKey(parsedQuery.sqlStatement, parsedQuery.parameters, options);
|
|
39
|
+
// When the component is suspended, all state is discarded. We don't get
|
|
40
|
+
// any notification of that. So checkoutQuery reserves a temporary hold
|
|
41
|
+
// on the query.
|
|
42
|
+
// Once the component "commits", we exchange that for a permanent hold.
|
|
43
|
+
const store = getQueryStore(powerSync);
|
|
44
|
+
const q = store.getQuery(key, { rawQuery: query, sqlStatement: parsedQuery.sqlStatement, queryParameters: parsedQuery.parameters }, options);
|
|
45
|
+
const addedHoldTo = React.useRef(undefined);
|
|
46
|
+
const releaseTemporaryHold = React.useRef(undefined);
|
|
47
|
+
if (addedHoldTo.current !== q) {
|
|
48
|
+
releaseTemporaryHold.current?.();
|
|
49
|
+
releaseTemporaryHold.current = q.addTemporaryHold();
|
|
50
|
+
addedHoldTo.current = q;
|
|
51
|
+
}
|
|
52
|
+
const [_counter, setUpdateCounter] = React.useState(0);
|
|
53
|
+
React.useEffect(() => {
|
|
54
|
+
const dispose = q.registerListener({
|
|
55
|
+
onUpdate: () => {
|
|
56
|
+
setUpdateCounter((counter) => {
|
|
57
|
+
return counter + 1;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
releaseTemporaryHold.current?.();
|
|
62
|
+
releaseTemporaryHold.current = undefined;
|
|
63
|
+
return dispose;
|
|
64
|
+
}, []);
|
|
65
|
+
if (q.currentError != null) {
|
|
66
|
+
throw q.currentError;
|
|
67
|
+
}
|
|
68
|
+
else if (q.currentData != null) {
|
|
69
|
+
return { data: q.currentData, refresh: () => q.fetchData() };
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
throw q.readyPromise;
|
|
73
|
+
}
|
|
74
|
+
};
|
package/lib/index.d.ts
CHANGED
|
@@ -2,5 +2,6 @@ export * from './hooks/PowerSyncContext';
|
|
|
2
2
|
export { usePowerSyncQuery } from './hooks/usePowerSyncQuery';
|
|
3
3
|
export { useStatus } from './hooks/useStatus';
|
|
4
4
|
export { useQuery } from './hooks/useQuery';
|
|
5
|
+
export { useSuspenseQuery } from './hooks/useSuspenseQuery';
|
|
5
6
|
export { usePowerSyncWatchedQuery } from './hooks/usePowerSyncWatchedQuery';
|
|
6
7
|
export { usePowerSyncStatus } from './hooks/usePowerSyncStatus';
|
package/lib/index.js
CHANGED
|
@@ -2,5 +2,6 @@ export * from './hooks/PowerSyncContext';
|
|
|
2
2
|
export { usePowerSyncQuery } from './hooks/usePowerSyncQuery';
|
|
3
3
|
export { useStatus } from './hooks/useStatus';
|
|
4
4
|
export { useQuery } from './hooks/useQuery';
|
|
5
|
+
export { useSuspenseQuery } from './hooks/useSuspenseQuery';
|
|
5
6
|
export { usePowerSyncWatchedQuery } from './hooks/usePowerSyncWatchedQuery';
|
|
6
7
|
export { usePowerSyncStatus } from './hooks/usePowerSyncStatus';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@powersync/react",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"registry": "https://registry.npmjs.org/",
|
|
6
6
|
"access": "public"
|
|
@@ -22,14 +22,15 @@
|
|
|
22
22
|
},
|
|
23
23
|
"homepage": "https://docs.powersync.com",
|
|
24
24
|
"peerDependencies": {
|
|
25
|
-
"
|
|
26
|
-
"
|
|
25
|
+
"@powersync/common": "^1.19.0",
|
|
26
|
+
"react": "*"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@testing-library/react": "^15.0.2",
|
|
30
30
|
"@types/react": "^18.2.34",
|
|
31
31
|
"jsdom": "^24.0.0",
|
|
32
32
|
"react": "18.2.0",
|
|
33
|
+
"react-error-boundary": "^4.1.0",
|
|
33
34
|
"typescript": "^5.5.3"
|
|
34
35
|
},
|
|
35
36
|
"scripts": {
|