1import type { VNode } from 'preact';
2import type { AnyVariables, DocumentInput } from '@urql/core';
3
4import type { UseMutationState, UseMutationExecute } from '../hooks';
5import { useMutation } from '../hooks';
6
7/** Props accepted by {@link Mutation}.
8 *
9 * @remarks
10 * `MutationProps` are the props accepted by the {@link Mutation} component.
11 *
12 * The result, the {@link MutationState} object, will be passed to
13 * a {@link MutationProps.children} function, passed as children
14 * to the `Mutation` component.
15 */
16export interface MutationProps<
17 Data = any,
18 Variables extends AnyVariables = AnyVariables,
19> {
20 /* The GraphQL mutation document that {@link useMutation} will execute. */
21 query: DocumentInput<Data, Variables>;
22 children(arg: MutationState<Data, Variables>): VNode<any>;
23}
24
25/** Object that {@link MutationProps.children} is called with.
26 *
27 * @remarks
28 * This is an extented {@link UseMutationstate} with an added
29 * {@link MutationState.executeMutation} method, which is usually
30 * part of a tuple returned by {@link useMutation}.
31 */
32export interface MutationState<
33 Data = any,
34 Variables extends AnyVariables = AnyVariables,
35> extends UseMutationState<Data, Variables> {
36 /** Alias to {@link useMutation}’s `executeMutation` function. */
37 executeMutation: UseMutationExecute<Data, Variables>;
38}
39
40/** Component Wrapper around {@link useMutation} to run a GraphQL query.
41 *
42 * @remarks
43 * `Mutation` is a component wrapper around the {@link useMutation} hook
44 * that calls the {@link MutationProps.children} prop, as a function,
45 * with the {@link MutationState} object.
46 */
47export function Mutation<
48 Data = any,
49 Variables extends AnyVariables = AnyVariables,
50>(props: MutationProps<Data, Variables>): VNode<any> {
51 const mutation = useMutation<Data, Variables>(props.query);
52 return props.children({ ...mutation[0], executeMutation: mutation[1] });
53}