@powersync/react 1.5.3 → 1.7.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 +16 -0
  10. package/lib/hooks/suspense/suspense-utils.js +75 -0
  11. package/lib/hooks/suspense/useSingleSuspenseQuery.d.ts +10 -0
  12. package/lib/hooks/suspense/useSingleSuspenseQuery.js +72 -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 +51 -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 +11 -7
  33. package/lib/index.js +9 -7
  34. package/package.json +10 -4
  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
@@ -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>;
@@ -1,126 +0,0 @@
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,25 +0,0 @@
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>;
@@ -1,74 +0,0 @@
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
- };