-
Notifications
You must be signed in to change notification settings - Fork 58
feature: added useSuspenseQuery
hook to react package
#353
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
8c286be
feature: added `useSuspenseQuery` hook to `react` package
Chriztiaan 7f6f088
Merge branch 'main' into react/suspense
Chriztiaan e8f8085
Added readme entry for useSuspenseQuery.
Chriztiaan b891d32
Resetting timeout indefinitely instead of only once.
Chriztiaan 0a09ee3
Added QueryStore tests.
Chriztiaan 82fa744
Added test suite for useSuspenseQuery.
Chriztiaan 75897f4
Import cleanup.
Chriztiaan 782b70e
WatchedQuery now extends BaseObserver.
Chriztiaan c1f96ac
Implementing Disposable interface.
Chriztiaan 341ab00
Added a jsdoc example snippet.
Chriztiaan 4b24ec9
Merge branch 'main' into react/suspense
Chriztiaan 21eb137
Readme polish
benitav 7921c71
Update packages/vue/README.md
benitav 0b708c8
Merge branch 'main' into react/suspense
Chriztiaan 4126515
Merge branch 'react/suspense' of github.com:powersync-ja/powersync-js…
Chriztiaan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'@powersync/react': minor | ||
--- | ||
|
||
Added `useSuspenseQuery` hook, allowing queries to suspend instead of returning `isLoading`/`isFetching` state. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import { AbstractPowerSyncDatabase, CompilableQuery, SQLWatchOptions } from '@powersync/common'; | ||
import { Query, WatchedQuery } from './WatchedQuery'; | ||
|
||
export class QueryStore { | ||
cache = new Map<string, WatchedQuery>(); | ||
|
||
constructor(private db: AbstractPowerSyncDatabase) {} | ||
|
||
getQuery(key: string, query: Query<unknown>, options: SQLWatchOptions) { | ||
if (this.cache.has(key)) { | ||
return this.cache.get(key); | ||
} | ||
const disposer = () => { | ||
this.cache.delete(key); | ||
}; | ||
const q = new WatchedQuery(this.db, query, options, disposer); | ||
this.cache.set(key, q); | ||
|
||
return q; | ||
} | ||
} | ||
|
||
let queryStores: WeakMap<AbstractPowerSyncDatabase, QueryStore> | undefined = undefined; | ||
|
||
export function getQueryStore(db: AbstractPowerSyncDatabase): QueryStore { | ||
queryStores ||= new WeakMap(); | ||
const existing = queryStores.get(db); | ||
if (existing) { | ||
return existing; | ||
} | ||
const store = new QueryStore(db); | ||
queryStores.set(db, store); | ||
return store; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
import { AbstractPowerSyncDatabase, CompilableQuery, QueryResult, SQLWatchOptions } from '@powersync/common'; | ||
import { AdditionalOptions } from 'src/hooks/useQuery'; | ||
|
||
export class Query<T> { | ||
rawQuery: string | CompilableQuery<T>; | ||
sqlStatement: string; | ||
queryParameters: any[]; | ||
} | ||
|
||
export class WatchedQuery { | ||
listeners = new Set<() => void>(); | ||
|
||
readyPromise: Promise<void>; | ||
isReady: boolean = false; | ||
currentData: any[] | undefined; | ||
currentError: any; | ||
tables: any[] | undefined; | ||
|
||
private temporaryHolds = new Set(); | ||
private controller: AbortController | undefined; | ||
private db: AbstractPowerSyncDatabase; | ||
|
||
private resolveReady: undefined | (() => void); | ||
|
||
readonly query: Query<unknown>; | ||
readonly options: AdditionalOptions; | ||
private disposer: () => void; | ||
|
||
constructor(db: AbstractPowerSyncDatabase, query: Query<unknown>, options: AdditionalOptions, disposer: () => void) { | ||
this.db = db; | ||
this.query = query; | ||
this.options = options; | ||
this.disposer = disposer; | ||
|
||
this.readyPromise = new Promise((resolve) => { | ||
this.resolveReady = resolve; | ||
}); | ||
} | ||
|
||
addTemporaryHold() { | ||
const ref = new Object(); | ||
this.temporaryHolds.add(ref); | ||
this.maybeListen(); | ||
|
||
let timeout: any; | ||
const release = () => { | ||
this.temporaryHolds.delete(ref); | ||
if (timeout) { | ||
clearTimeout(timeout); | ||
} | ||
this.maybeDispose(); | ||
}; | ||
|
||
const timeoutRelease = () => { | ||
if (this.isReady || this.controller == null) { | ||
release(); | ||
} else { | ||
// If the query is taking long, keep the temporary hold. | ||
timeout = setTimeout(release, 5_000); | ||
} | ||
}; | ||
|
||
timeout = setTimeout(timeoutRelease, 5_000); | ||
|
||
return release; | ||
} | ||
|
||
addListener(l: () => void) { | ||
this.listeners.add(l); | ||
|
||
this.maybeListen(); | ||
return () => { | ||
this.listeners.delete(l); | ||
this.maybeDispose(); | ||
}; | ||
} | ||
|
||
private async fetchTables() { | ||
try { | ||
this.tables = await this.db.resolveTables(this.query.sqlStatement, this.query.queryParameters, this.options); | ||
} catch (e) { | ||
console.error('Failed to fetch tables:', e); | ||
this.setError(e); | ||
} | ||
} | ||
|
||
async fetchData() { | ||
try { | ||
const result = | ||
typeof this.query.rawQuery == 'string' | ||
? await this.db.getAll(this.query.sqlStatement, this.query.queryParameters) | ||
: await this.query.rawQuery.execute(); | ||
|
||
const data = result ?? []; | ||
this.setData(data); | ||
} catch (e) { | ||
console.error('Failed to fetch data:', e); | ||
this.setError(e); | ||
} | ||
} | ||
|
||
private maybeListen() { | ||
if (this.controller != null) { | ||
return; | ||
} | ||
if (this.listeners.size == 0 && this.temporaryHolds.size == 0) { | ||
return; | ||
} | ||
|
||
const controller = new AbortController(); | ||
this.controller = controller; | ||
|
||
const onError = (error: Error) => { | ||
this.setError(error); | ||
}; | ||
|
||
(async () => { | ||
await this.fetchTables(); | ||
await this.fetchData(); | ||
|
||
if (!this.options.runQueryOnce) { | ||
this.db.onChangeWithCallback( | ||
{ | ||
onChange: async () => { | ||
await this.fetchData(); | ||
}, | ||
onError | ||
}, | ||
{ | ||
...this.options, | ||
signal: this.controller.signal, | ||
tables: this.tables | ||
} | ||
); | ||
} | ||
})(); | ||
} | ||
|
||
private setData(results: any[]) { | ||
this.isReady = true; | ||
this.currentData = results; | ||
this.currentError = undefined; | ||
this.resolveReady?.(); | ||
|
||
for (let listener of this.listeners) { | ||
listener(); | ||
} | ||
} | ||
|
||
private setError(error: any) { | ||
this.isReady = true; | ||
this.currentData = undefined; | ||
this.currentError = error; | ||
this.resolveReady?.(); | ||
|
||
for (let listener of this.listeners) { | ||
listener(); | ||
} | ||
} | ||
|
||
private maybeDispose() { | ||
if (this.listeners.size == 0 && this.temporaryHolds.size == 0) { | ||
this.controller?.abort(); | ||
this.controller = undefined; | ||
this.isReady = false; | ||
this.currentData = undefined; | ||
this.currentError = undefined; | ||
this.disposer?.(); | ||
|
||
this.readyPromise = new Promise((resolve, reject) => { | ||
this.resolveReady = resolve; | ||
}); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.