Svelte Query 09 ⚡ Mutations — Executing create, update, and delete with createMutation
While queries are designed to fetch data, mutations are specifically designed to change server state. In a modern application, a mutation is not just a network request; it is a complex lifecycle that involves managing loading states, handling server errors, potentially performing optimistic updates, and synchronizing the local cache with the newly updated server-side state. TanStack Query provides a robust createMutation primitive to standardize these operations.
This chapter covers the core mechanics of mutations, including the difference between the fire-and-forget mutate function and the promise-based mutateAsync. We will also explore the powerful lifecycle callbacks that allow you to trigger UI side-effects, such as invalidating query keys or displaying toast notifications, ensuring that your application’s state remains perfectly aligned with the server after every write operation.
Key point: createMutation manages the full lifecycle of data-changing requests, providing reactive state tracking for pending, success, and error outcomes while offering standardized lifecycle hooks to perform cache invalidations and UI side effects immediately upon server confirmation.
Why exists
The manual state management burden. Managing isLoading, isError, and data flags for every API request is tedious and error-prone. createMutation encapsulates this state, providing a single reactive object that tells your UI exactly what phase the mutation is in.
The synchronization gap. After a mutation succeeds, your existing query cache is often stale. Developers must manually trigger refetches or invalidations. createMutation integrates directly with the QueryClient, making cache invalidation a first-class citizen of the mutation lifecycle.
The race condition risk. Submitting the same form multiple times can lead to inconsistent server state or duplicate entries. By tracking the isPending flag, you can easily disable submit buttons or prevent concurrent triggers, providing a safer user experience.
The error feedback loop. Handling server errors requires consistent UI patterns. createMutation captures errors uniformly, allowing you to use global onError callbacks to show notifications without repeating logic in every form component.
The complexity of asynchronous workflows. Sometimes you need to wait for a mutation to finish before navigating or executing follow-up logic. mutateAsync provides the necessary promise interface to integrate mutations into standard async/await flows cleanly.
a. The createMutation primitive and mutate
The createMutation hook defines the mutation logic. Unlike queries, mutations are not “active” by default; they wait for you to call the mutate function. This function takes your input data, passes it to the mutationFn, and tracks the status in the returned state object.
const mutation = createMutation({
mutationFn: (newPost) => fetch('/api/posts', {
method: 'POST',
body: JSON.stringify(newPost)
})
});
// Triggering the mutation
<button on:click={() => $mutation.mutate({ title: 'New Post' })}>
{ $mutation.isPending ? 'Saving...' : 'Save' }
</button>
The mutate function is a fire-and-forget interface. It is perfect for standard form submissions where you don’t necessarily need to catch the result in the local scope, as the state is handled reactively by the $mutation object itself.
b. Managing state with lifecycle callbacks
The mutation lifecycle provides four primary hooks: onMutate, onSuccess, onError, and onSettled. onMutate runs before the request is sent, onSuccess runs after a successful response, onError handles failures, and onSettled runs regardless of the outcome. These are the ideal places to handle cache invalidation.
const mutation = createMutation({
mutationFn: updateProfile,
onSuccess: () => {
// Invalidate the user profile cache to force a refetch
queryClient.invalidateQueries({ queryKey: ['user'] });
},
onError: (err) => {
showToast('Failed to update profile');
}
});
Using these callbacks ensures that your UI responds to data changes immediately. By invalidating the ['user'] key in onSuccess, you ensure that the next time any component uses the user data, it will be the most recent version provided by the server.
c. mutateAsync and promise-based flow
While mutate is convenient for simple UI interactions, mutateAsync returns a promise that resolves when the mutation completes. This is useful when your mutation is part of a larger, complex function—such as navigating to a new route only after a resource is successfully created.
async function handleSave() {
try {
await $mutation.mutateAsync(data);
goto('/dashboard'); // Navigate only on success
} catch (err) {
// Handle error locally if needed
}
}
mutateAsync gives you the flexibility to mix Svelte Query’s reactive state tracking with imperative async/await control flow. However, be cautious: unlike mutate, you are responsible for handling errors in a try/catch block, as the mutation will throw if the mutationFn fails.
Complete Example Session
// ============================================
// PART 1: DEFINING THE MUTATION
// ============================================
const mutation = createMutation({
mutationFn: (data) => api.post('/todos', data),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
onError: (err) => alert(err.message)
});
// ============================================
// PART 2: UI BINDING
// ============================================
<button
disabled={$mutation.isPending}
on:click={() => $mutation.mutate({ title: 'Learn Svelte' })}
>
{$mutation.isPending ? 'Adding...' : 'Add Todo'}
</button>
// ============================================
// PART 3: ASYNC FLOW
// ============================================
async function save() {
await $mutation.mutateAsync({ title: 'Async Save' });
console.log('Saved successfully!');
}
// ============================================
// PART 4: OPTIMISTIC UI (Briefly)
// ============================================
// onMutate can be used to set local state
// while waiting for server confirmation.
The session illustrates defining a mutation, binding it to a UI button with pending-state protection, utilizing the async promise flow, and adding cache invalidation.
Quick Reference
Mutation Lifecycle
| Hook | Timing | Purpose |
|---|---|---|
onMutate | Before | Prep data / Optimistic update |
onSuccess | After | Invalidate cache / Notify |
onError | Failure | Logging / Error UI |
onSettled | Finish | Cleanup |
Mutation Methods
| Method | Return | Use Case |
|---|---|---|
mutate | void | Fire-and-forget UI updates |
mutateAsync | Promise | Complex async workflows |
Best Practices
✅ Do This:
// Invalidate cache on success
onSuccess: () => queryClient.invalidateQueries(['list']); // ✅
// Track pending state for UI
<button disabled={$mutation.isPending}>Submit</button> // ✅
// Handle errors globally or per mutation
onError: (e) => log(e); // ✅
// Use mutate for standard actions
$mutation.mutate(data); // ✅
❌ Don’t Do This:
// Don't refetch manually after mutation
// (Use invalidateQueries) // ❌
// Don't forget to handle the error state
// (The user needs feedback) // ❌
// Don't use mutateAsync if mutate is sufficient
// (It creates unnecessary try/catch blocks) // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| UI Stale | Missing invalidateQueries | Use onSuccess callback |
| Race Conditions | Concurrent mutate calls | Use isPending to disable |
| Silent Failure | Missing onError | Add global error logging |
| Object Memory | Improper mutateAsync usage | Stick to mutate by default |
Real-World Examples
1. Simple POST
createMutation({ mutationFn: (data) => fetch('/api', ...) })
2. Cache Invalidation
onSuccess: () => qc.invalidateQueries({ queryKey: ['data'] })
3. Error Toast
onError: () => toast.error('Request failed')
4. Disable Button
disabled={$mutation.isPending}
5. Async Navigation
await $mutation.mutateAsync(data); goto('/next');
6. Form Submission
$mutation.mutate(new FormData(form))
7. Global Settled
onSettled: () => console.log('Finished')
8. Complex Cleanup
onSettled: () => resetForm()
9. Typed Mutation
createMutation<Data, Error, Variables>({...})
10. Optimistic Update (via onMutate)
onMutate: () => { ... }
Visual
The Mutation Pipeline
┌──────────────────────────────────────────────┐
│ MUTATE(VARIABLES) │
│ │ │
│ [onMutate] ──► Prep State │
│ │ │
│ [mutationFn] ──► API Request │
│ │ │
│ [onSuccess / onError] ──► Sync Cache │
│ │ │
│ [onSettled] ──► Cleanup │
└──────────────────────────────────────────────┘
State Transition
┌──────────────────────────────────────────────┐
│ IDLE ──► PENDING (mutate) │
│ │ │
│ ├─► SUCCESS (onSuccess) │
│ └─► ERROR (onError) │
│ │
│ All paths lead to SETTLED │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
createMutation | State-managed write operations |
mutate | Simple, reactive interface |
mutateAsync | Promise-based flow |
onSuccess | Best place for invalidation |
isPending | Reactive loading state |
Key takeaways:
- Standardize your writes. Use
createMutationfor all server-state mutations to centralize loading, error, and success state logic. - Cache invalidation is automatic. Always tie your
onSuccesscallback toqueryClient.invalidateQueriesto ensure your UI displays fresh data after a write. - Use
isPendingfor UX. Never let a user click a save button twice; use the reactive$mutation.isPendingflag to disable inputs during processing. - Choose the right interface. Default to
mutatefor simplicity; reach formutateAsynconly when you need to chain operations based on the mutation result. - Don’t ignore the error. Always implement an
onErroror global error boundary to ensure that your users are alerted if their request fails.
Remember: Mutations are the bridge between your clean UI and the server’s state. By using createMutation to handle the heavy lifting of state transitions and cache synchronization, you shift your development focus away from managing request lifecycles and toward building expressive, interactive features that behave predictably under any network condition.
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!