useMutation
Composable for executing GraphQL mutations.
Quick start
import { useMutation } from 'vue3-apollo'
import { CREATE_USER } from './gql'
const {
data,
error,
loading,
mutate,
onDone,
} = useMutation(
CREATE_USER,
)
async function submit() {
await mutate({
email: '[email protected]',
name: 'John',
})
}
onDone((payload) => {
console.log('Created:', payload)
})
API
const {
mutate,
data,
loading,
error,
called,
onDone,
onError,
reset,
} = useMutation(document, options?)
Returns
mutate(variables?, mutateOptions?)
→Promise<Result | void>
– execute the mutation. Per‑call options override base options.tsawait mutate( { id: '1', name: 'Jane' }, { optimisticResponse: { updateUser: { __typename: 'User', id: '1', name: 'Jane' }, }, refetchQueries: ['GetUserList'], } )
data
– reactive result data (undefined until success).loading
–true
while the mutation is running.error
– GraphQL or network error if one occurred.called
–true
aftermutate()
has been called at least once.onDone((data, context) => {})
– Fires when the mutation completes successfully. Thecontext
provides access to the Apollo client.tsonDone((data, context) => { toast.success('User created!') router.push(`/users/${data.createUser.id}`) context.client.cache.evict({ fieldName: 'users' }) })
onError((error, context) => {})
– Fires when the mutation encounters an error (network or GraphQL). Thecontext
contains the active Apollo client.tsonError((error, context) => { toast.error(error.message) console.error('Mutation failed:', error) context.client.clearStore() })
reset()
– cleardata
,error
,loading
, andcalled
back to initial state.
Options
Pass as the second argument to useMutation
.
throws
:'always' | 'auto' | 'never'
(default:'auto'
)'always'
: throw on error (usetry/catch
).'never'
: never throw; rely on reactiveerror
&onError
.'auto'
: Apollo default behavior.
- Apollo mutate options (except
mutation
&variables
, which are provided):refetchQueries
,awaitRefetchQueries
,optimisticResponse
,update
,context
, etc. clientId
(fromUseBaseOption
) – target a specific Apollo client if you registered multiple.