diff --git a/packages/vue-apollo-composable/src/index.ts b/packages/vue-apollo-composable/src/index.ts index 362987a..b75a520 100644 --- a/packages/vue-apollo-composable/src/index.ts +++ b/packages/vue-apollo-composable/src/index.ts @@ -1,4 +1,5 @@ export * from './useQuery' +export * from './useMutation' export * from './useResult' // export * from './useLoading' export * from './useApolloClient' diff --git a/packages/vue-apollo-composable/src/useMutation.ts b/packages/vue-apollo-composable/src/useMutation.ts new file mode 100644 index 0000000..00df3de --- /dev/null +++ b/packages/vue-apollo-composable/src/useMutation.ts @@ -0,0 +1,62 @@ +import { DocumentNode } from 'graphql' +import { MutationOptions, OperationVariables } from 'apollo-client' +import { ref } from '@vue/composition-api' +import { useApolloClient } from './useApolloClient' +import { ReactiveFunction } from './util/ReactiveFunction' + +export interface UseMutationOptions< + TResult = any, + TVariables = OperationVariables +> extends Omit, 'mutation'> { + clientId?: string +} + +export function useMutation< + TResult = any, + TVariables = OperationVariables +> ( + document: DocumentNode, + options: UseMutationOptions | ReactiveFunction> = null, +) { + if (!options) options = {} + + const loading = ref(false) + const error = ref(null) + + // Apollo Client + const { resolveClient } = useApolloClient() + + async function mutate (variables: TVariables = null) { + let currentOptions: UseMutationOptions + if (typeof options === 'function') { + currentOptions = options() + } else { + currentOptions = options + } + const client = resolveClient(currentOptions.clientId) + error.value = null + loading.value = true + try { + const result = await client.mutate({ + mutation: document, + ...currentOptions, + variables: { + ...variables || {}, + ...currentOptions.variables || {}, + }, + }) + loading.value = false + return result + } catch (e) { + error.value = e + loading.value = false + throw e + } + } + + return { + mutate, + loading, + error, + } +} \ No newline at end of file