Skip to content

@vue/apollo-composable / useMutation

Function: useMutation() ​

useMutation(mutation, options?): Result

A composable for executing GraphQL mutations.

Parameters ​

mutation ​

MaybeRefOrGetter<DocumentNode>

A GraphQL mutation document.

options? ​

MaybeRefOrGetter<Options>

Options to control how the mutation is executed.

Returns ​

Result

Mutation result object with reactive refs and mutate function.

Example ​

vue
<script setup lang="ts">
import { useMutation } from '@vue/apollo-composable'
import gql from 'graphql-tag'

const AddTodo = gql`mutation AddTodo($text: String!) { addTodo(text: $text) { id text } }`

const { mutate, loading, error, onDone, onError } = useMutation(AddTodo)

onDone((result) => {
  console.log('Todo added:', result.data)
})

onError((error) => {
  console.error('Failed:', error.message)
})

async function addTodo(text: string) {
  await mutate({ variables: { text } })
}
</script>

<template>
  <button @click="addTodo('New task')" :disabled="loading">
    {{ loading ? 'Adding...' : 'Add Todo' }}
  </button>
  <p v-if="error">Error: {{ error.message }}</p>
</template>

Released under the MIT License.