@@ -20,7 +20,7 @@ export type QueryResult<T> = {
20
20
/**
21
21
* Function used to run the query again.
22
22
*/
23
- refresh ?: ( ) => Promise < void > ;
23
+ refresh ?: ( signal ?: AbortSignal ) => Promise < void > ;
24
24
} ;
25
25
26
26
/**
@@ -95,21 +95,31 @@ export const useQuery = <T = any>(
95
95
setError ( wrappedError ) ;
96
96
} ;
97
97
98
- const fetchData = async ( ) => {
98
+ const fetchData = async ( signal ?: AbortSignal ) => {
99
99
setIsFetching ( true ) ;
100
100
try {
101
101
const result =
102
102
typeof query == 'string' ? await powerSync . getAll < T > ( sqlStatement , queryParameters ) : await query . execute ( ) ;
103
+
104
+ if ( signal ?. aborted ) {
105
+ return ;
106
+ }
107
+
103
108
handleResult ( result ) ;
104
109
} catch ( e ) {
105
110
console . error ( 'Failed to fetch data:' , e ) ;
106
111
handleError ( e ) ;
107
112
}
108
113
} ;
109
114
110
- const fetchTables = async ( ) => {
115
+ const fetchTables = async ( signal ?: AbortSignal ) => {
111
116
try {
112
117
const tables = await powerSync . resolveTables ( sqlStatement , memoizedParams , memoizedOptions ) ;
118
+
119
+ if ( signal ?. aborted ) {
120
+ return ;
121
+ }
122
+
113
123
setTables ( tables ) ;
114
124
} catch ( e ) {
115
125
console . error ( 'Failed to fetch tables:' , e ) ;
@@ -118,9 +128,10 @@ export const useQuery = <T = any>(
118
128
} ;
119
129
120
130
React . useEffect ( ( ) => {
131
+ const abortController = new AbortController ( ) ;
121
132
const updateData = async ( ) => {
122
- await fetchTables ( ) ;
123
- await fetchData ( ) ;
133
+ await fetchTables ( abortController . signal ) ;
134
+ await fetchData ( abortController . signal ) ;
124
135
} ;
125
136
126
137
updateData ( ) ;
@@ -129,7 +140,10 @@ export const useQuery = <T = any>(
129
140
schemaChanged : updateData
130
141
} ) ;
131
142
132
- return ( ) => l ?.( ) ;
143
+ return ( ) => {
144
+ abortController . abort ( ) ;
145
+ l ?.( ) ;
146
+ } ;
133
147
} , [ powerSync , memoizedParams , sqlStatement ] ) ;
134
148
135
149
React . useEffect ( ( ) => {
@@ -141,7 +155,7 @@ export const useQuery = <T = any>(
141
155
powerSync . onChangeWithCallback (
142
156
{
143
157
onChange : async ( ) => {
144
- await fetchData ( ) ;
158
+ await fetchData ( abortController . current . signal ) ;
145
159
} ,
146
160
onError ( e ) {
147
161
handleError ( e ) ;
0 commit comments