| | |

Vue Query 09 ⚡ Mutations — Executing create/update/delete requests with mutate, mutateAsync, and lifecycle callbacks

⏱️ Estimated read: 10 min | |

In web development, the majority of application logic revolves around reading data from a server. However, real-world applications are defined by their ability to change that data. Creating, updating, and deleting (CUD operations) is inherently more complex than reading. You must handle loading states, manage errors, keep the UI in sync with the server, and ideally, provide instant feedback through optimistic updates. Manually managing these states using ref or reactive variables often results in repetitive, bug-prone code scattered throughout your components.

Vue Query’s useMutation hook is the declarative solution to these challenges. It provides a standardized lifecycle for writing data, abstracting away the state management associated with HTTP requests. Whether you are posting a new form, updating a user profile, or deleting an item, useMutation gives you a consistent API to track the status of your request, handle successful completions, and perform rollbacks in the event of an error.

This chapter covers the full mechanics of mutations in Vue Query. We will explore the difference between mutate and mutateAsync, the sequence of lifecycle callbacks, and the advanced pattern of optimistic updates—where you update the UI before the server even responds, creating an “instant” feel that is characteristic of high-quality web applications.

Key point: useMutation is the engine for server-side state modification; it manages loading states, provides hooks for side effects (like invalidation or toast notifications), and enables optimistic UI updates to keep your application fast and resilient.


Why exists

The Loading State Labor. Without a mutation library, every “Submit” button requires a local state variable like isSaving or isDeleting. You have to remember to set it to true at the start of a request, false on success, and false on error. useMutation eliminates this boilerplate by providing a unified isPending status flag.

The “Ghost” Data Problem. After a successful mutation, the server state has changed, but your local cache (the query data) is still stale. If you don’t manually invalidate the cache, your UI will continue to show old data. Mutations exist to facilitate the “Invalidation” pattern—automatically marking queries as stale and triggering a refetch the moment a write operation succeeds.

The Latency Illusion (Optimistic Updates). In a high-latency network, waiting for a server response to show a “Like” count increment feels sluggish. Mutations allow you to perform “Optimistic Updates,” where you pretend the mutation succeeded, update the UI immediately, and silently roll back if the server request actually fails.

The Error Handling Consistency. Tracking and logging errors manually across different HTTP services is inconsistent. useMutation provides a dedicated onError hook that standardizes how your application captures, logs, and displays mutation failures, whether they happen in a form submission or a background background sync.

The Imperative vs. Declarative Shift. Mutations are inherently imperative (triggered by user action) compared to Queries (which are often declarative). useMutation bridges this gap, allowing you to trigger imperative actions while still using the declarative status flags (success, error, pending) that make the rest of Vue Query so powerful.


a. The Mutation Lifecycle (mutate vs mutateAsync)

The primary function of useMutation is the mutate method. It is designed for “fire-and-forget” scenarios. It accepts your variables and executes the mutationFn. Crucially, mutate does not return a promise—you cannot await it. Instead, you handle the result using the callback lifecycle hooks.

const { mutate } = useMutation({
  mutationFn: updateProfile,
});

// Triggering the mutation
mutate({ name: 'Alice' });

Conversely, mutateAsync returns a standard Promise. This is preferred when you need to chain operations (e.g., submit a form, then redirect the user, then clear a local store). Using mutateAsync allows you to await the request and use standard try/catch blocks, which is often more readable when dealing with complex control flows.

const { mutateAsync } = useMutation({
  mutationFn: updateProfile,
});

async function handleSubmit() {
  try {
    await mutateAsync({ name: 'Alice' });
    router.push('/dashboard'); // Only runs if mutation succeeds
  } catch (error) {
    console.error('Submission failed', error);
  }
}

Do not mix mutate and mutateAsync in the same component logic without careful consideration. Using mutate keeps your code strictly reactive and declarative, while mutateAsync provides imperative control. Choose one style per feature to maintain consistency.


b. Lifecycle Callbacks

The power of useMutation lies in its ability to orchestrate side effects through four specific lifecycle hooks: onMutate, onSuccess, onError, and onSettled. These hooks form the bridge between your server request and your UI/Cache logic.

  1. onMutate: Runs before the mutationFn. This is where you perform “Optimistic Updates” by capturing the current state (to roll back later) and manually updating the QueryCache.
  2. onSuccess: Runs when the mutation finishes successfully. This is the primary location for invalidating queries (e.g., queryClient.invalidateQueries(['users'])) and showing “Success” notifications.
  3. onError: Runs when the mutation fails. This is used for rolling back optimistic updates and showing “Error” notifications.
  4. onSettled: Runs after either onSuccess or onError. This is useful for “cleanup” tasks that must happen regardless of the outcome, such as closing a modal or resetting a loading state.
useMutation({
  mutationFn: deleteTodo,
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ['todos'] });
  },
  onError: (error) => {
    toast.error(error.message);
  }
});

c. Advanced Orchestration: Optimistic Updates

Optimistic updates allow your UI to react instantly to user input. The pattern is a “transaction”: you update the cache, perform the network request, and if the network fails, you revert the cache change. This is orchestrated through the context object passed between the hooks.

const mutation = useMutation({
  mutationFn: updateTodo,
  onMutate: async (newTodo) => {
    // 1. Cancel outgoing refetches (so they don't overwrite our optimistic update)
    await queryClient.cancelQueries({ queryKey: ['todos'] });

    // 2. Snapshot the previous value
    const previousTodos = queryClient.getQueryData(['todos']);

    // 3. Optimistically update to the new value
    queryClient.setQueryData(['todos'], (old) => [...old, newTodo]);

    // 4. Return context object with snapshotted value
    return { previousTodos };
  },
  onError: (err, newTodo, context) => {
    // 5. Rollback on error
    queryClient.setQueryData(['todos'], context.previousTodos);
  },
  onSettled: () => {
    // 6. Always refetch after error or success to sync with server
    queryClient.invalidateQueries({ queryKey: ['todos'] });
  },
});

The context object is the secret to a perfect rollback. By returning the previous state in onMutate, you ensure that onError has access to the exact data snapshot from before the mutation attempt, preventing data corruption during a failed request.


Complete Example Session

// ============================================
// PART 1: BASIC MUTATION
// ============================================
const { mutate } = useMutation({
  mutationFn: (data: FormData) => axios.post('/api/upload', data)
});

// ============================================
// PART 2: MUTATE ASYNC
// ============================================
const { mutateAsync } = useMutation({ mutationFn: createPost });

const onSubmit = async () => {
  const result = await mutateAsync(formData);
  console.log('Post created:', result);
};

// ============================================
// PART 3: SUCCESS INVALIDATION
// ============================================
const { mutate: deleteItem } = useMutation({
  mutationFn: deleteRequest,
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ['items'] });
  }
});

// ============================================
// PART 4: ERROR HANDLING
// ============================================
const { mutate: update } = useMutation({
  mutationFn: updateReq,
  onError: (err) => alert(`Update failed: ${err.message}`)
});

// ============================================
// PART 5: OPTIMISTIC UPDATE (Setup)
// ============================================
const { mutate: toggleLike } = useMutation({
  mutationFn: likePost,
  onMutate: async (newStatus) => {
    await queryClient.cancelQueries({ queryKey: ['posts'] });
    const prev = queryClient.getQueryData(['posts']);
    queryClient.setQueryData(['posts'], (old) => updateStatus(old, newStatus));
    return { prev };
  },
  // ... onError/onSettled
});

// ============================================
// PART 6: ROLLBACK LOGIC
// ============================================
// onError: (err, variables, context) => {
//   queryClient.setQueryData(['posts'], context.prev);
// }

// ============================================
// PART 7: SETTLED HOOK
// ============================================
// onSettled: () => queryClient.invalidateQueries(['posts'])

// ============================================
// PART 8: RESETTING MUTATION STATE
// ============================================
const { reset } = useMutation({ ... });
// reset(); // Clears isError / isSuccess status

// ============================================
// PART 9: MULTIPLE MUTATIONS IN ONE COMPONENT
// ============================================
// useMutation({ mutationFn: A })
// useMutation({ mutationFn: B })

// ============================================
// PART 10: VARIABLES ACCESS IN CALLBACKS
// ============================================
// onSuccess: (data, variables) => { 
//   console.log('ID used:', variables.id); 
// }

The sequence above covered the basics of mutation methods, lifecycle orchestration, and the crucial optimistic update pattern for high-performance UIs.


Quick Reference

Mutation Methods

MethodReturn TypeUse Case
mutatevoidFire-and-forget, simple UI interactions
mutateAsyncPromiseChained logic, router redirects, error handling
resetvoidClearing status flags (isSuccess/isError)

Lifecycle Hooks

HookReceivesPurpose
onMutatevariablesOptimistic updates, snapshotting state
onSuccessdata, varsCache invalidation, success messages
onErrorerror, vars, contextCache rollback, error notifications
onSettleddata/err, vars, contextUI cleanup, final sync

Status Flags

FlagDescription
isPendingMutation is currently in flight
isSuccessMutation succeeded (last attempt)
isErrorMutation failed (last attempt)
isIdleMutation hasn’t started yet

Best Practices

✅ Do This:

// Invalidate related queries on success
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['list'] }); // ✅

// Use mutateAsync for redirects or chained promises
await mutateAsync(data); router.push('/success');          // ✅

// Always cancel existing queries before an optimistic update
await queryClient.cancelQueries({ queryKey: [...] });      // ✅

// Provide a stable mutationFn reference (e.g. from service file)
mutationFn: userService.updateUser                         // ✅

❌ Don’t Do This:

// Don't mix mutate and mutateAsync in one component
// Don't forget to rollback in onError during optimistic updates
// Don't update local component state manually if you can rely on the cache
// Don't trigger mutations in the render loop (watch for triggers)

Common Pitfalls

PitfallWhy It HappensFix
Race ConditionsConcurrent mutations overwriting cacheUse cancelQueries in onMutate
Lost ErrorsUsing mutate without onErrorProvide onError callback or use mutateAsync
UI JitterUpdating cache after request finishesUse optimistic updates (onMutate)
Unhandled RejectionsUsing mutateAsync without try/catchWrap in try/catch or handle via callback
Stale CacheForgetting invalidateQueriesUse onSuccess or onSettled to invalidate

Real-World Examples

1. Form Submission

const { mutate } = useMutation({ mutationFn: submitForm, onSuccess: () => router.push('/') })

2. Deleting an Item

onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] })

3. Optimistic Like Button

onMutate: async (id) => { ...update UI... return { prev } },
onError: (err, id, ctx) => { ...restore prev... }

4. Async Chain

await mutateAsync(data); showToast();

5. Resetting Form Status

onSuccess: () => { form.reset(); reset(); }

6. Global Mutation Error Logger

onError: (err) => Sentry.capture(err)

7. Passing Variables to Success

onSuccess: (data, variables) => console.log(`Edited user ${variables.id}`)

8. Throttling Mutations

// use a lock or isPending flag

9. Mutating with Context

onMutate: () => ({ startTime: Date.now() }),
onSettled: (data, err, vars, ctx) => console.log(Date.now() - ctx.startTime)

10. Sequential Mutations

await mutateAsync(step1); await mutateAsync(step2);

Visual

The Mutation Status Lifecycle

┌──────────────────────────────────────────────────────────┐
│ IDLE ───(mutate)───► PENDING ───(request)───► SUCCESS    │
│  ^                      │                        │       │
│  └──────(reset)─────────┴──────(error)───────────┘       │
│                                                          │
│ (Note: Success/Error states persist until next mutate    │
│  or reset() is called)                                   │
└──────────────────────────────────────────────────────────┘

Optimistic Update Flow

┌─────────────┐      ┌───────────────┐      ┌─────────────┐
│  USER ACTION│      │ ONMUTATE      │      │  SERVER     │
│  (Click)    │────► │ 1. Cancel     │────► │  (Request)  │
└─────────────┘      │ 2. Snapshot   │      └──────┬──────┘
                     │ 3. Optimistic │             │
                     └──────┬────────┘             │
                            │                      │
                     ┌──────▼────────┐             │
                     │  ONERROR      │ ◄───────────┘
                     │  Rollback!    │
                     └───────────────┘

Summary

ItemValue
Main HookuseMutation
Trigger Methodmutate (void) or mutateAsync (promise)
LifecycleonMutate -> onSuccess/onError -> onSettled
SyncingqueryClient.invalidateQueries
UX PatternOptimistic Updates
Resetreset()

Key takeaways:

  • Use mutate for simplicity. If you don’t need to chain promises or catch errors locally, mutate provides the cleanest, most reactive interface for CUD operations .
  • Use mutateAsync for orchestration. If you need to chain network requests, redirect the user, or handle errors with try/catch in a logical flow, mutateAsync is the correct tool .
  • Invalidation is mandatory. Mutations change server state. You must always use onSuccess or onSettled to invalidate the relevant query keys so your UI reflects the new reality .
  • Master the Optimistic Update. This is the secret to high-performance UIs. Snapshot your state, update it early, and be prepared to roll back if the server fails .
  • Handle errors globally or locally. You can provide onError hooks to the mutation for local logic and register global mutation caches to report errors to services like Sentry .
  • Cleanup with onSettled. Always use onSettled for tasks that must run regardless of the result, like stopping a global loading spinner or closing a side drawer .

Remember: useMutation isn’t just about sending data; it’s about managing the “Write Lifecycle” of your application. Use the hooks to orchestrate your UI, cache, and error reporting, and your data layer will become significantly more robust.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!