Last active
September 30, 2021 12:00
-
-
Save younesmln/f07aa16dfa829848a8b3a4be70f0721a 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 { | |
TypedDocumentNode, | |
useMutation, | |
UseMutationResponse, | |
useQuery, | |
UseQueryArgs, | |
UseQueryResponse, | |
} from 'urql'; | |
type Data<Document> = Document extends TypedDocumentNode<infer Data> | |
? Data | |
: unknown; | |
type Vars<Document> = Document extends TypedDocumentNode<unknown, infer Vars> | |
? Vars | |
: unknown; | |
export function useGraphqlCRUD< | |
Query extends TypedDocumentNode, | |
CreateMutation extends TypedDocumentNode, | |
DeleteMutation extends TypedDocumentNode | |
>({ | |
query, | |
context, | |
variables, | |
createMutation, | |
deleteMutation, | |
}: { | |
query: Query; | |
variables: Vars<Query>; | |
context: UseQueryArgs['context']; | |
createMutation: CreateMutation; | |
deleteMutation: DeleteMutation; | |
}) { | |
const [response] = useQuery({ | |
query, | |
variables, | |
context, | |
}) as UseQueryResponse<Data<Query>, Vars<Query>>; | |
const [, createOperation] = useMutation( | |
createMutation | |
) as UseMutationResponse<Data<CreateMutation>, Vars<CreateMutation>>; | |
const [, deleteOperation] = useMutation( | |
deleteMutation | |
) as UseMutationResponse<Data<DeleteMutation>, Vars<DeleteMutation>>; | |
return { | |
response, | |
createOperation, | |
deleteOperation, | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage example