Skip to content

Commit

Permalink
feat: useMutation
Browse files Browse the repository at this point in the history
  • Loading branch information
Guillaume Chau committed Nov 29, 2019
1 parent 764027a commit c8a7eca
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
1 change: 1 addition & 0 deletions 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'
62 changes: 62 additions & 0 deletions 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<MutationOptions<TResult, TVariables>, 'mutation'> {
clientId?: string
}

export function useMutation<
TResult = any,
TVariables = OperationVariables
> (
document: DocumentNode,
options: UseMutationOptions<TResult, TVariables> | ReactiveFunction<UseMutationOptions<TResult, TVariables>> = null,
) {
if (!options) options = {}

const loading = ref<boolean>(false)
const error = ref<Error>(null)

// Apollo Client
const { resolveClient } = useApolloClient()

async function mutate (variables: TVariables = null) {
let currentOptions: UseMutationOptions<TResult, TVariables>
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,
}
}

0 comments on commit c8a7eca

Please sign in to comment.