Skip to content

Commit

Permalink
WatchedQuery now extends BaseObserver.
Browse files Browse the repository at this point in the history
  • Loading branch information
Chriztiaan committed Oct 17, 2024
1 parent 75897f4 commit 782b70e
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 16 deletions.
23 changes: 11 additions & 12 deletions packages/react/src/WatchedQuery.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AbstractPowerSyncDatabase, CompilableQuery } from '@powersync/common';
import { AbstractPowerSyncDatabase, BaseListener, BaseObserver, CompilableQuery } from '@powersync/common';
import { AdditionalOptions } from './hooks/useQuery';

export class Query<T> {
Expand All @@ -7,9 +7,11 @@ export class Query<T> {
queryParameters: any[];
}

export class WatchedQuery {
listeners = new Set<() => void>();
export interface WatchedQueryListener extends BaseListener {
onUpdate: () => void;
}

export class WatchedQuery extends BaseObserver<WatchedQueryListener> {
readyPromise: Promise<void>;
isReady: boolean = false;
currentData: any[] | undefined;
Expand All @@ -27,6 +29,7 @@ export class WatchedQuery {
private disposer: () => void;

constructor(db: AbstractPowerSyncDatabase, query: Query<unknown>, options: AdditionalOptions, disposer: () => void) {
super();
this.db = db;
this.query = query;
this.options = options;
Expand Down Expand Up @@ -65,12 +68,12 @@ export class WatchedQuery {
return release;
}

addListener(l: () => void) {
this.listeners.add(l);
registerListener(listener: Partial<WatchedQueryListener>): () => void {
const disposer = super.registerListener(listener);

this.maybeListen();
return () => {
this.listeners.delete(l);
disposer();
this.maybeDispose();
};
}
Expand Down Expand Up @@ -142,9 +145,7 @@ export class WatchedQuery {
this.currentError = undefined;
this.resolveReady?.();

for (let listener of this.listeners) {
listener();
}
this.iterateListeners((l) => l?.onUpdate());
}

private setError(error: any) {
Expand All @@ -153,9 +154,7 @@ export class WatchedQuery {
this.currentError = error;
this.resolveReady?.();

for (let listener of this.listeners) {
listener();
}
this.iterateListeners((l) => l?.onUpdate());
}

private maybeDispose() {
Expand Down
10 changes: 6 additions & 4 deletions packages/react/src/hooks/useSuspenseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,12 @@ export const useSuspenseQuery = <T = any>(
const [_counter, setUpdateCounter] = React.useState(0);

React.useEffect(() => {
const dispose = q.addListener(() => {
setUpdateCounter((counter) => {
return counter + 1;
});
const dispose = q.registerListener({
onUpdate: () => {
setUpdateCounter((counter) => {
return counter + 1;
});
}
});

releaseTemporaryHold.current?.();
Expand Down

0 comments on commit 782b70e

Please sign in to comment.