Skip to content

Commit

Permalink
Add a count of active query watchers
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonmade committed May 30, 2024
1 parent d58b911 commit 442f69a
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
6 changes: 6 additions & 0 deletions .changeset/clean-deers-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@quilted/preact-async': patch
'@quilted/async': patch
---

Add a count of active query watchers
3 changes: 2 additions & 1 deletion packages/async/source/AsyncActionCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class AsyncActionCache {
const initialCache = this.#initialCache.get(id);
action = create(initialCache) as any as AsyncActionCacheEntry<Action>;

Object.assign(action, {id, key, tags});
Object.assign(action, {id, key, tags, watchers: 0});
this.#cache.set(id, action);

return action;
Expand Down Expand Up @@ -234,6 +234,7 @@ export type AsyncActionCacheEntry<
readonly id: string;
readonly key: AsyncActionCacheKey;
readonly tags: readonly string[];
watchers: number;
};

export type AsyncActionCacheEntrySerialization<
Expand Down
12 changes: 12 additions & 0 deletions packages/preact-async/source/hooks/async.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,19 @@ export function useAsync<Data = unknown, Input = unknown>(
const action = actionSignal.value;

useEffect(() => {
const actionAsCacheEntry =
'watchers' in action && typeof action.watchers === 'number'
? action
: undefined;

if (actionAsCacheEntry) actionAsCacheEntry.watchers += 1;

return () => {
if (actionAsCacheEntry) {
actionAsCacheEntry.watchers -= 1;
if (actionAsCacheEntry.watchers > 0) return;
}

// TODO: don’t abort if there are other listeners?
action.running?.abort();
};
Expand Down

0 comments on commit 442f69a

Please sign in to comment.