Skip to content

Commit 48dc2cb

Browse files
committed
Fix useQuery race condition for initial query.
1 parent 974b852 commit 48dc2cb

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

.changeset/slimy-glasses-jog.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
'@powersync/react': patch
3+
'@powersync/react-native': patch
4+
---
5+
6+
Fixed an issue with `useQuery` where initial query/parameter changes could cause a race condition if the first query took long.

packages/react/src/hooks/useQuery.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,16 @@ export const useQuery = <T = any>(
9595
setError(wrappedError);
9696
};
9797

98-
const fetchData = async () => {
98+
const fetchData = async (signal?: AbortSignal) => {
9999
setIsFetching(true);
100100
try {
101101
const result =
102102
typeof query == 'string' ? await powerSync.getAll<T>(sqlStatement, queryParameters) : await query.execute();
103+
104+
if (signal?.aborted) {
105+
return;
106+
}
107+
103108
handleResult(result);
104109
} catch (e) {
105110
console.error('Failed to fetch data:', e);
@@ -118,9 +123,10 @@ export const useQuery = <T = any>(
118123
};
119124

120125
React.useEffect(() => {
126+
const abortController = new AbortController();
121127
const updateData = async () => {
122128
await fetchTables();
123-
await fetchData();
129+
await fetchData(abortController.signal);
124130
};
125131

126132
updateData();
@@ -129,7 +135,10 @@ export const useQuery = <T = any>(
129135
schemaChanged: updateData
130136
});
131137

132-
return () => l?.();
138+
return () => {
139+
abortController.abort();
140+
l?.();
141+
};
133142
}, [powerSync, memoizedParams, sqlStatement]);
134143

135144
React.useEffect(() => {

0 commit comments

Comments
 (0)