Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/slimy-glasses-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@powersync/react': patch
'@powersync/react-native': patch
---

Fixed an issue with `useQuery` where initial query/parameter changes could cause a race condition if the first query took long.
28 changes: 21 additions & 7 deletions packages/react/src/hooks/useQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export type QueryResult<T> = {
/**
* Function used to run the query again.
*/
refresh?: () => Promise<void>;
refresh?: (signal?: AbortSignal) => Promise<void>;
};

/**
Expand Down Expand Up @@ -95,21 +95,31 @@ export const useQuery = <T = any>(
setError(wrappedError);
};

const fetchData = async () => {
const fetchData = async (signal?: AbortSignal) => {
setIsFetching(true);
try {
const result =
typeof query == 'string' ? await powerSync.getAll<T>(sqlStatement, queryParameters) : await query.execute();

if (signal?.aborted) {
return;
}

handleResult(result);
} catch (e) {
console.error('Failed to fetch data:', e);
handleError(e);
}
};

const fetchTables = async () => {
const fetchTables = async (signal?: AbortSignal) => {
try {
const tables = await powerSync.resolveTables(sqlStatement, memoizedParams, memoizedOptions);

if (signal?.aborted) {
return;
}

setTables(tables);
} catch (e) {
console.error('Failed to fetch tables:', e);
Expand All @@ -118,9 +128,10 @@ export const useQuery = <T = any>(
};

React.useEffect(() => {
const abortController = new AbortController();
const updateData = async () => {
await fetchTables();
await fetchData();
await fetchTables(abortController.signal);
await fetchData(abortController.signal);
};

updateData();
Expand All @@ -129,7 +140,10 @@ export const useQuery = <T = any>(
schemaChanged: updateData
});

return () => l?.();
return () => {
abortController.abort();
l?.();
};
}, [powerSync, memoizedParams, sqlStatement]);

React.useEffect(() => {
Expand All @@ -141,7 +155,7 @@ export const useQuery = <T = any>(
powerSync.onChangeWithCallback(
{
onChange: async () => {
await fetchData();
await fetchData(abortController.current.signal);
},
onError(e) {
handleError(e);
Expand Down