Created
May 17, 2022 10:12
-
-
Save betafcc/54d5b6935bfe245b514050608a541afa to your computer and use it in GitHub Desktop.
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
import { DocumentNode } from 'graphql' | |
import { | |
gql, | |
QueryHookOptions, | |
QueryResult, | |
TypedDocumentNode, | |
useQuery, | |
} from '@apollo/client' | |
export type Query<TData, TVariables> = | |
| DocumentNode | |
| TypedDocumentNode<TData, TVariables> | |
export type RawQuery<TData, TVariables> = string | Query<TData, TVariables> | |
/** | |
* While we don't have a codegen, this helper can improve the typing of our queries | |
* | |
* @example | |
* const useStoreQuery = makeSimpleUseQuery<{ id: string }, { slug: string }>(` | |
* query Store(slug: String!) { | |
* store(slug: $slug) { | |
* id | |
* } | |
* }` | |
* ) | |
* | |
* const result = useStoreQuery({ slug: 'foo' }) // { data: { id: '123' } } | |
* | |
* // also keeps query reference if needed | |
* result.query | |
*/ | |
export const makeSimpleUseQuery: { | |
<TData = any>(rawQuery: RawQuery<TData, {}>): { | |
query: Query<TData, {}> | |
(variables?: any, options?: QueryHookOptions<TData, {}>): QueryResult< | |
TData, | |
{} | |
> | |
} | |
<TData, TVariables>(rawQuery: RawQuery<TData, TVariables>): { | |
query: Query<TData, TVariables> | |
( | |
variables: TVariables, | |
options?: QueryHookOptions<TData, TVariables>, | |
): QueryResult<TData, TVariables> | |
} | |
} = (rawQuery: any) => { | |
const query = typeof rawQuery === 'string' ? gql(rawQuery) : rawQuery | |
const f = (variables: any, options = {}) => | |
useQuery(query, { variables, ...options }) | |
f.query = query | |
return f | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment