-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathuseWatchedQuery.ts
More file actions
63 lines (55 loc) · 2.22 KB
/
useWatchedQuery.ts
File metadata and controls
63 lines (55 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import React from 'react';
import { useNullableWatchedQuerySubscription } from './useWatchedQuerySubscription.js';
import { DifferentialHookOptions, QueryResult, ReadonlyQueryResult } from './watch-types.js';
import { InternalHookOptions } from './watch-utils.js';
/**
* @internal This is not exported from the index.ts
*
* When an incremental query is used the return type is readonly. This is required
* since the implementation requires a stable ref.
* For legacy compatibility we allow mutating when a standard query is used. Mutations should
* not affect the internal implementation in this case.
*/
export const useWatchedQuery = <RowType = unknown>(
options: InternalHookOptions<RowType[]> & { options: DifferentialHookOptions<RowType> }
): QueryResult<RowType> | ReadonlyQueryResult<RowType> => {
const { query, powerSync, queryChanged, options: hookOptions, active } = options;
const queryChangeRef = React.useRef(false);
if (queryChanged && !queryChangeRef.current) {
queryChangeRef.current = true;
}
function createWatchedQuery() {
if (!active) {
return null;
}
const watch = hookOptions.rowComparator
? powerSync.customQuery(query).differentialWatch({
rowComparator: hookOptions.rowComparator,
reportFetching: hookOptions.reportFetching,
throttleMs: hookOptions.throttleMs
})
: powerSync.customQuery(query).watch({
reportFetching: hookOptions.reportFetching,
throttleMs: hookOptions.throttleMs
});
return watch;
}
const [watchedQuery, setWatchedQuery] = React.useState(createWatchedQuery);
React.useEffect(() => {
watchedQuery?.close();
setWatchedQuery(createWatchedQuery);
}, [powerSync, active]);
// Indicates that the query will be re-fetched due to a change in the query.
// Used when `isFetching` hasn't been set to true yet due to React execution.
React.useEffect(() => {
if (queryChangeRef.current) {
watchedQuery?.updateSettings({
query,
throttleMs: hookOptions.throttleMs,
reportFetching: hookOptions.reportFetching
});
queryChangeRef.current = false;
}
}, [queryChangeRef.current]);
return useNullableWatchedQuerySubscription(watchedQuery);
};