Skip to content

Commit

Permalink
Allow keying a GraphQLQuery
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonmade committed May 26, 2024
1 parent a3ccf09 commit 5e88a4f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 18 deletions.
5 changes: 5 additions & 0 deletions .changeset/fluffy-beds-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@quilted/preact-graphql': patch
---

Allow keying a `GraphQLQuery`
47 changes: 29 additions & 18 deletions packages/preact-graphql/source/hooks/use-graphql-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import {
type GraphQLFetch,
type GraphQLAnyOperation,
} from '@quilted/graphql';
import type {ReadonlySignal} from '@quilted/preact-signals';
import {
computed,
resolveSignalOrValue,
type ReadonlySignal,
} from '@quilted/preact-signals';
import {
useAsync,
useAsyncActionCache,
Expand All @@ -21,6 +25,7 @@ export function useGraphQLQuery<Data, Variables>(
tags,
signal,
suspend,
key,
active: explicitActive,
cache: explicitCache,
fetch: explicitFetch,
Expand All @@ -29,7 +34,7 @@ export function useGraphQLQuery<Data, Variables>(
variables?: Variables | ReadonlySignal<Variables>;
} & Pick<
UseAsyncActionOptions<Data, Variables>,
'active' | 'signal' | 'suspend' | 'cache' | 'tags'
'active' | 'signal' | 'suspend' | 'cache' | 'tags' | 'key'
> = {},
) {
const fetchFromContext = useGraphQLFetch({optional: true});
Expand All @@ -53,22 +58,28 @@ export function useGraphQLQuery<Data, Variables>(
throw new Error('No cache provided for GraphQL query.');
}

const queryAction = useMemo(
() =>
cache
? cache.create((cached) => new GraphQLQuery(query, {fetch, cached}), {
key: `query:${
typeof query === 'string'
? query
: 'id' in query
? query.id
: toGraphQLSource(query)
}`,
tags,
})
: new GraphQLQuery(query, {fetch}),
[query, fetch, cache],
);
const queryAction = useMemo(() => {
if (cache == null) {
return new GraphQLQuery(query, {fetch});
}

const queryKey = `graphql:${
typeof query === 'string'
? query
: 'id' in query
? query.id
: toGraphQLSource(query)
}`;

const fullKey = key
? computed(() => [queryKey, resolveSignalOrValue(key)].flat(1))
: queryKey;

return cache.create((cached) => new GraphQLQuery(query, {fetch, cached}), {
key: fullKey,
tags,
});
}, [query, fetch, cache, key]);

const active =
explicitActive ?? (typeof document === 'object' || Boolean(cache));
Expand Down

0 comments on commit 5e88a4f

Please sign in to comment.