Skip to content

Instantly share code, notes, and snippets.

@betafcc
Created May 17, 2022 10:12
Show Gist options
  • Save betafcc/54d5b6935bfe245b514050608a541afa to your computer and use it in GitHub Desktop.
Save betafcc/54d5b6935bfe245b514050608a541afa to your computer and use it in GitHub Desktop.
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