Skip to content

Commit

Permalink
feat: suspense subquery
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewPattell committed Jun 7, 2024
1 parent e04a980 commit c2a2fff
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/suspense-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ interface ISuspenseQueryParams {
errorFields?: string[];
}

interface ISuspenseSubqueryOptions {
id: string;
hash: unknown;
}

/**
* Run request and cache promise
* Sync suspense status between server and client
Expand All @@ -22,6 +27,11 @@ class SuspenseQuery {
*/
protected promise: Promise<any> | undefined;

/**
* Subqueries info
*/
protected subqueries: Map<string, { hash: unknown; promise?: IPromise<any> }> = new Map();

/**
* Target store
*/
Expand Down Expand Up @@ -136,6 +146,36 @@ class SuspenseQuery {
return SuspenseQuery.run<TReturn>(this.promise);
};

/**
* Run subquery
* Re-fetch data from query by hash changes in children components
* NOTE: only client side
*/
public subquery = <TReturn>(
promise: () => Promise<TReturn>,
options: ISuspenseSubqueryOptions,
): TReturn | undefined => {
const { id, hash } = options;
const subquery = this.subqueries.get(id);

// skip first run
if (!subquery) {
this.subqueries.set(id, { hash });

return undefined;
}

if (subquery?.hash === hash) {
return SuspenseQuery.run<TReturn>(subquery?.promise);
}

const newQuery = promise();

this.subqueries.set(id, { hash, promise: newQuery });

return SuspenseQuery.run<TReturn>(newQuery);
};

/**
* Change status of promise.
* Throw promise to react suspense
Expand Down

0 comments on commit c2a2fff

Please sign in to comment.