API Documentation / @pinia/colada / defineMutation
Function: defineMutation() 
Call Signature 
ts
function defineMutation<TData, TVars, TError, TContext>(options): () => UseMutationReturn<TData, TVars, TError>;Define a mutation with the given options. Similar to useMutation(options) but allows you to reuse the mutation in multiple places.
Type Parameters 
TData 
TData
TVars 
TVars = void
TError 
TError = { custom: Error; }
TContext 
TContext extends Record<any, any> = _EmptyObject
Parameters 
options 
UseMutationOptions<TData, TVars, TError, TContext>
the options to define the mutation
Returns 
ts
(): UseMutationReturn<TData, TVars, TError>;Returns 
UseMutationReturn<TData, TVars, TError>
Example 
ts
const useCreateTodo = defineMutation({
  mutation: (todoText: string) =>
    fetch('/api/todos', {
      method: 'POST',
      body: JSON.stringify({ text: todoText }),
    }),
})Call Signature 
ts
function defineMutation<T>(setup): () => T;Define a mutation with a function setup. Allows to return arbitrary values from the mutation function, create contextual refs, rename the returned values, etc.
Type Parameters 
T 
T
Parameters 
setup 
() => T
a function to setup the mutation
Returns 
ts
(): T;Returns 
T
Example 
ts
const useCreateTodo = defineMutation(() => {
  const todoText = ref('')
  const { data, mutate, ...rest } = useMutation({
    mutation: () =>
      fetch('/api/todos', {
        method: 'POST',
        body: JSON.stringify({ text: todoText.value }),
      }),
  })
  // expose the todoText ref and rename other methods for convenience
  return { ...rest, createTodo: mutate, todo: data, todoText }
})