@powersync/react 1.5.3 → 1.6.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.
Files changed (43) hide show
  1. package/README.md +146 -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 +39 -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 +62 -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 +6 -3
  35. package/lib/WatchedQuery.d.ts +0 -36
  36. package/lib/WatchedQuery.js +0 -148
  37. package/lib/hooks/useQuery.d.ts +0 -34
  38. package/lib/hooks/useQuery.js +0 -126
  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
@@ -0,0 +1,39 @@
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
+ * // Providing a `rowComparator` results in the hook using an incremental query under the hood.
21
+ * // An incremental query will only emit results when a change to the result set occurs.
22
+ * // The internal array object references are maintained for unchanged rows.
23
+ * // The returned lists array is read only when a `rowComparator` is provided.
24
+ * const { data: lists } = useQuery('SELECT * from lists', [], {
25
+ * rowComparator: {
26
+ * keyBy: (item) => item.id,
27
+ * compareBy: (item) => JSON.stringify(item)
28
+ * }
29
+ * });
30
+ *
31
+ * return <View>
32
+ * {lists.map((l) => (
33
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
34
+ * ))}
35
+ * </View>
36
+ * }
37
+ */
38
+ export declare function useQuery<RowType = any>(query: string | CompilableQuery<RowType>, parameters?: any[], options?: AdditionalOptions): QueryResult<RowType>;
39
+ export declare function useQuery<RowType = any>(query: string | CompilableQuery<RowType>, parameters?: any[], options?: DifferentialHookOptions<RowType>): ReadonlyQueryResult<RowType>;
@@ -0,0 +1,32 @@
1
+ import { usePowerSync } from '../PowerSyncContext';
2
+ import { useSingleQuery } from './useSingleQuery';
3
+ import { useWatchedQuery } from './useWatchedQuery';
4
+ import { constructCompatibleQuery } from './watch-utils';
5
+ export function useQuery(query, parameters = [], options = {}) {
6
+ const powerSync = usePowerSync();
7
+ if (!powerSync) {
8
+ return { isLoading: false, isFetching: false, data: [], error: new Error('PowerSync not configured.') };
9
+ }
10
+ const { parsedQuery, queryChanged } = constructCompatibleQuery(query, parameters, options);
11
+ switch (options?.runQueryOnce) {
12
+ case true:
13
+ return useSingleQuery({
14
+ query: parsedQuery,
15
+ powerSync,
16
+ queryChanged
17
+ });
18
+ default:
19
+ return useWatchedQuery({
20
+ query: parsedQuery,
21
+ powerSync,
22
+ queryChanged,
23
+ options: {
24
+ reportFetching: options.reportFetching,
25
+ // Maintains backwards compatibility with previous versions
26
+ // Differentiation is opt-in by default
27
+ // We emit new data for each table change by default.
28
+ rowComparator: options.rowComparator
29
+ }
30
+ });
31
+ }
32
+ }
@@ -0,0 +1,3 @@
1
+ import { QueryResult } from './watch-types';
2
+ import { InternalHookOptions } from './watch-utils';
3
+ export declare const useSingleQuery: <RowType = any>(options: InternalHookOptions<RowType[]>) => QueryResult<RowType>;
@@ -0,0 +1,52 @@
1
+ import React from 'react';
2
+ export const useSingleQuery = (options) => {
3
+ const { query, powerSync, queryChanged } = options;
4
+ const [output, setOutputState] = React.useState({
5
+ isLoading: true,
6
+ isFetching: true,
7
+ data: [],
8
+ error: undefined
9
+ });
10
+ const runQuery = React.useCallback(async (signal) => {
11
+ setOutputState((prev) => ({ ...prev, isLoading: true, isFetching: true, error: undefined }));
12
+ try {
13
+ const compiledQuery = query.compile();
14
+ const result = await query.execute({
15
+ sql: compiledQuery.sql,
16
+ parameters: [...compiledQuery.parameters],
17
+ db: powerSync
18
+ });
19
+ if (signal.aborted) {
20
+ return;
21
+ }
22
+ setOutputState((prev) => ({
23
+ ...prev,
24
+ isLoading: false,
25
+ isFetching: false,
26
+ data: result,
27
+ error: undefined
28
+ }));
29
+ }
30
+ catch (error) {
31
+ setOutputState((prev) => ({
32
+ ...prev,
33
+ isLoading: false,
34
+ isFetching: false,
35
+ data: [],
36
+ error
37
+ }));
38
+ }
39
+ }, [queryChanged, query]);
40
+ // Trigger initial query execution
41
+ React.useEffect(() => {
42
+ const abortController = new AbortController();
43
+ runQuery(abortController.signal);
44
+ return () => {
45
+ abortController.abort();
46
+ };
47
+ }, [powerSync, queryChanged]);
48
+ return {
49
+ ...output,
50
+ refresh: runQuery
51
+ };
52
+ };
@@ -0,0 +1,13 @@
1
+ import { DifferentialHookOptions, QueryResult, ReadonlyQueryResult } from './watch-types';
2
+ import { InternalHookOptions } from './watch-utils';
3
+ /**
4
+ * @internal This is not exported from the index.ts
5
+ *
6
+ * When an incremental query is used the return type is readonly. This is required
7
+ * since the implementation requires a stable ref.
8
+ * For legacy compatibility we allow mutating when a standard query is used. Mutations should
9
+ * not affect the internal implementation in this case.
10
+ */
11
+ export declare const useWatchedQuery: <RowType = unknown>(options: InternalHookOptions<RowType[]> & {
12
+ options: DifferentialHookOptions<RowType>;
13
+ }) => QueryResult<RowType> | ReadonlyQueryResult<RowType>;
@@ -0,0 +1,43 @@
1
+ import React from 'react';
2
+ import { useWatchedQuerySubscription } from './useWatchedQuerySubscription';
3
+ /**
4
+ * @internal This is not exported from the index.ts
5
+ *
6
+ * When an incremental query is used the return type is readonly. This is required
7
+ * since the implementation requires a stable ref.
8
+ * For legacy compatibility we allow mutating when a standard query is used. Mutations should
9
+ * not affect the internal implementation in this case.
10
+ */
11
+ export const useWatchedQuery = (options) => {
12
+ const { query, powerSync, queryChanged, options: hookOptions } = options;
13
+ const createWatchedQuery = React.useCallback(() => {
14
+ const watch = hookOptions.rowComparator
15
+ ? powerSync.customQuery(query).differentialWatch({
16
+ rowComparator: hookOptions.rowComparator,
17
+ reportFetching: hookOptions.reportFetching,
18
+ throttleMs: hookOptions.throttleMs
19
+ })
20
+ : powerSync.customQuery(query).watch({
21
+ reportFetching: hookOptions.reportFetching,
22
+ throttleMs: hookOptions.throttleMs
23
+ });
24
+ return watch;
25
+ }, []);
26
+ const [watchedQuery, setWatchedQuery] = React.useState(createWatchedQuery);
27
+ React.useEffect(() => {
28
+ watchedQuery.close();
29
+ setWatchedQuery(createWatchedQuery);
30
+ }, [powerSync]);
31
+ // Indicates that the query will be re-fetched due to a change in the query.
32
+ // Used when `isFetching` hasn't been set to true yet due to React execution.
33
+ React.useEffect(() => {
34
+ if (queryChanged) {
35
+ watchedQuery.updateSettings({
36
+ query,
37
+ throttleMs: hookOptions.throttleMs,
38
+ reportFetching: hookOptions.reportFetching
39
+ });
40
+ }
41
+ }, [queryChanged]);
42
+ return useWatchedQuerySubscription(watchedQuery);
43
+ };
@@ -0,0 +1,16 @@
1
+ import { WatchedQuery } from '@powersync/common';
2
+ /**
3
+ * A hook to access and subscribe to the results of an existing {@link WatchedQuery} instance.
4
+ * @example
5
+ * export const ContentComponent = () => {
6
+ * const { data: lists } = useWatchedQuerySubscription(listsQuery);
7
+ *
8
+ * return <View>
9
+ * {lists.map((l) => (
10
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
11
+ * ))}
12
+ * </View>;
13
+ * }
14
+ *
15
+ */
16
+ export declare const useWatchedQuerySubscription: <ResultType = unknown, Query extends WatchedQuery<ResultType> = WatchedQuery<ResultType>>(query: Query) => Query["state"];
@@ -0,0 +1,29 @@
1
+ import React from 'react';
2
+ /**
3
+ * A hook to access and subscribe to the results of an existing {@link WatchedQuery} instance.
4
+ * @example
5
+ * export const ContentComponent = () => {
6
+ * const { data: lists } = useWatchedQuerySubscription(listsQuery);
7
+ *
8
+ * return <View>
9
+ * {lists.map((l) => (
10
+ * <Text key={l.id}>{JSON.stringify(l)}</Text>
11
+ * ))}
12
+ * </View>;
13
+ * }
14
+ *
15
+ */
16
+ export const useWatchedQuerySubscription = (query) => {
17
+ const [output, setOutputState] = React.useState(query.state);
18
+ React.useEffect(() => {
19
+ const dispose = query.registerListener({
20
+ onStateChange: (state) => {
21
+ setOutputState({ ...state });
22
+ }
23
+ });
24
+ return () => {
25
+ dispose();
26
+ };
27
+ }, [query]);
28
+ return output;
29
+ };
@@ -0,0 +1,62 @@
1
+ import { DifferentialWatchedQueryComparator, SQLOnChangeOptions } from '@powersync/common';
2
+ export interface HookWatchOptions extends Omit<SQLOnChangeOptions, 'signal'> {
3
+ reportFetching?: boolean;
4
+ }
5
+ export interface AdditionalOptions extends HookWatchOptions {
6
+ runQueryOnce?: boolean;
7
+ }
8
+ export interface DifferentialHookOptions<RowType> extends HookWatchOptions {
9
+ /**
10
+ * Used to compare result sets.
11
+ *
12
+ * By default the hook will requery on any dependent table change. This will
13
+ * emit a new hook result even if the result set has not changed.
14
+ *
15
+ * Specifying a {@link DifferentialWatchedQueryComparator} will remove emissions for
16
+ * unchanged result sets.
17
+ * Furthermore, emitted `data` arrays will preserve object references between result set emissions
18
+ * for unchanged rows.
19
+ * @example
20
+ * ```javascript
21
+ * {
22
+ * rowComparator: {
23
+ * keyBy: (item) => item.id,
24
+ * compareBy: (item) => JSON.stringify(item)
25
+ * }
26
+ * }
27
+ * ```
28
+ */
29
+ rowComparator?: DifferentialWatchedQueryComparator<RowType>;
30
+ }
31
+ export type ReadonlyQueryResult<RowType> = {
32
+ readonly data: ReadonlyArray<Readonly<RowType>>;
33
+ /**
34
+ * 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.
35
+ */
36
+ readonly isLoading: boolean;
37
+ /**
38
+ * 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).
39
+ */
40
+ readonly isFetching: boolean;
41
+ readonly error: Error | undefined;
42
+ /**
43
+ * Function used to run the query again.
44
+ */
45
+ refresh?: (signal?: AbortSignal) => Promise<void>;
46
+ };
47
+ export type QueryResult<RowType> = {
48
+ data: RowType[];
49
+ /**
50
+ * 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.
51
+ */
52
+ isLoading: boolean;
53
+ /**
54
+ * 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).
55
+ */
56
+ isFetching: boolean;
57
+ error: Error | undefined;
58
+ /**
59
+ * Function used to run the query again.
60
+ */
61
+ refresh?: (signal?: AbortSignal) => Promise<void>;
62
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import { AbstractPowerSyncDatabase, CompilableQuery, WatchCompatibleQuery } from '@powersync/common';
2
+ import { AdditionalOptions } from './watch-types';
3
+ export type InternalHookOptions<DataType> = {
4
+ query: WatchCompatibleQuery<DataType>;
5
+ powerSync: AbstractPowerSyncDatabase;
6
+ queryChanged: boolean;
7
+ };
8
+ export declare const checkQueryChanged: <T>(query: WatchCompatibleQuery<T>, options: AdditionalOptions) => boolean;
9
+ export declare const constructCompatibleQuery: <RowType>(query: string | CompilableQuery<RowType>, parameters: any[], options: AdditionalOptions) => {
10
+ parsedQuery: WatchCompatibleQuery<RowType[]>;
11
+ queryChanged: boolean;
12
+ };
@@ -0,0 +1,56 @@
1
+ import React from 'react';
2
+ import { usePowerSync } from '../PowerSyncContext';
3
+ export const checkQueryChanged = (query, options) => {
4
+ let _compiled;
5
+ try {
6
+ _compiled = query.compile();
7
+ }
8
+ catch (error) {
9
+ return false; // If compilation fails, we assume the query has changed
10
+ }
11
+ const compiled = _compiled;
12
+ const stringifiedParams = JSON.stringify(compiled.parameters);
13
+ const stringifiedOptions = JSON.stringify(options);
14
+ const previousQueryRef = React.useRef({ sqlStatement: compiled.sql, stringifiedParams, stringifiedOptions });
15
+ if (previousQueryRef.current.sqlStatement !== compiled.sql ||
16
+ previousQueryRef.current.stringifiedParams != stringifiedParams ||
17
+ previousQueryRef.current.stringifiedOptions != stringifiedOptions) {
18
+ previousQueryRef.current.sqlStatement = compiled.sql;
19
+ previousQueryRef.current.stringifiedParams = stringifiedParams;
20
+ previousQueryRef.current.stringifiedOptions = stringifiedOptions;
21
+ return true;
22
+ }
23
+ return false;
24
+ };
25
+ export const constructCompatibleQuery = (query, parameters = [], options) => {
26
+ const powerSync = usePowerSync();
27
+ const parsedQuery = React.useMemo(() => {
28
+ if (typeof query == 'string') {
29
+ return {
30
+ compile: () => ({
31
+ sql: query,
32
+ parameters
33
+ }),
34
+ execute: () => powerSync.getAll(query, parameters)
35
+ };
36
+ }
37
+ else {
38
+ return {
39
+ // Generics differ a bit but holistically this is the same
40
+ compile: () => {
41
+ const compiled = query.compile();
42
+ return {
43
+ sql: compiled.sql,
44
+ parameters: [...compiled.parameters]
45
+ };
46
+ },
47
+ execute: () => query.execute()
48
+ };
49
+ }
50
+ }, [query, powerSync]);
51
+ const queryChanged = checkQueryChanged(parsedQuery, options);
52
+ return {
53
+ parsedQuery,
54
+ queryChanged
55
+ };
56
+ };
package/lib/index.d.ts CHANGED
@@ -1,7 +1,11 @@
1
+ export { usePowerSyncQuery } from './hooks/deprecated/usePowerSyncQuery';
2
+ export { usePowerSyncStatus } from './hooks/deprecated/usePowerSyncStatus';
3
+ export { usePowerSyncWatchedQuery } from './hooks/deprecated/usePowerSyncWatchedQuery';
1
4
  export * from './hooks/PowerSyncContext';
2
- export { usePowerSyncQuery } from './hooks/usePowerSyncQuery';
5
+ export { SuspenseQueryResult } from './hooks/suspense/SuspenseQueryResult';
6
+ export { useSuspenseQuery } from './hooks/suspense/useSuspenseQuery';
7
+ export { useWatchedQuerySuspenseSubscription } from './hooks/suspense/useWatchedQuerySuspenseSubscription';
3
8
  export { useStatus } from './hooks/useStatus';
4
- export { useQuery } from './hooks/useQuery';
5
- export { useSuspenseQuery } from './hooks/useSuspenseQuery';
6
- export { usePowerSyncWatchedQuery } from './hooks/usePowerSyncWatchedQuery';
7
- export { usePowerSyncStatus } from './hooks/usePowerSyncStatus';
9
+ export { useQuery } from './hooks/watched/useQuery';
10
+ export { useWatchedQuerySubscription } from './hooks/watched/useWatchedQuerySubscription';
11
+ export { AdditionalOptions } from './hooks/watched/watch-types';
package/lib/index.js CHANGED
@@ -1,7 +1,9 @@
1
+ export { usePowerSyncQuery } from './hooks/deprecated/usePowerSyncQuery';
2
+ export { usePowerSyncStatus } from './hooks/deprecated/usePowerSyncStatus';
3
+ export { usePowerSyncWatchedQuery } from './hooks/deprecated/usePowerSyncWatchedQuery';
1
4
  export * from './hooks/PowerSyncContext';
2
- export { usePowerSyncQuery } from './hooks/usePowerSyncQuery';
5
+ export { useSuspenseQuery } from './hooks/suspense/useSuspenseQuery';
6
+ export { useWatchedQuerySuspenseSubscription } from './hooks/suspense/useWatchedQuerySuspenseSubscription';
3
7
  export { useStatus } from './hooks/useStatus';
4
- export { useQuery } from './hooks/useQuery';
5
- export { useSuspenseQuery } from './hooks/useSuspenseQuery';
6
- export { usePowerSyncWatchedQuery } from './hooks/usePowerSyncWatchedQuery';
7
- export { usePowerSyncStatus } from './hooks/usePowerSyncStatus';
8
+ export { useQuery } from './hooks/watched/useQuery';
9
+ export { useWatchedQuerySubscription } from './hooks/watched/useWatchedQuerySubscription';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/react",
3
- "version": "1.5.3",
3
+ "version": "1.6.0",
4
4
  "publishConfig": {
5
5
  "registry": "https://registry.npmjs.org/",
6
6
  "access": "public"
@@ -22,16 +22,19 @@
22
22
  },
23
23
  "homepage": "https://docs.powersync.com",
24
24
  "peerDependencies": {
25
- "@powersync/common": "^1.28.0",
25
+ "@powersync/common": "^1.35.0",
26
26
  "react": "*"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@testing-library/react": "^15.0.2",
30
30
  "@types/react": "^18.3.1",
31
+ "chart.js": "^4.5.0",
31
32
  "jsdom": "^24.0.0",
32
33
  "react": "18.3.1",
34
+ "react-dom": "18.3.1",
33
35
  "react-error-boundary": "^4.1.0",
34
- "@powersync/common": "1.28.0"
36
+ "@powersync/common": "1.35.0",
37
+ "@powersync/web": "1.25.0"
35
38
  },
36
39
  "scripts": {
37
40
  "build": "tsc -b",
@@ -1,36 +0,0 @@
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(): any;
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
- }
@@ -1,148 +0,0 @@
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,34 +0,0 @@
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>;