Open History to see the last commit
1---
2id: mutations
3title: Mutations
4ref: docs/framework/react/guides/mutations.md
5---
6β
7[//]: # 'Example'
8β
9```vue
10<script setup>
11import { useMutation } from '@tanstack/vue-query'
12β
13const { isPending, isError, error, isSuccess, mutate } = useMutation({
14 mutationFn: (newTodo) => axios.post('/todos', newTodo),
15})
16β
17function addTodo() {
18 mutate({ id: new Date(), title: 'Do Laundry' })
19}
20</script>
21β
22<template>
23 <span v-if="isPending">Adding todo...</span>
24 <span v-else-if="isError">An error occurred: {{ error.message }}</span>
25 <span v-else-if="isSuccess">Todo added!</span>
26 <button @click="addTodo">Create Todo</button>
27</template>
28```
29β
30[//]: # 'Example'
31[//]: # 'Info1'
32[//]: # 'Info1'
33[//]: # 'Example2'
34[//]: # 'Example2'
35[//]: # 'Example3'
36β
37```vue
38<script setup>
39import { useMutation } from '@tanstack/vue-query'
40β
41const { error, mutate, reset } = useMutation({
42 mutationFn: (newTodo) => axios.post('/todos', newTodo),
43})
44β
45function addTodo() {
46 mutate({ id: new Date(), title: 'Do Laundry' })
47}
48</script>
49β
50<template>
51 <span v-if="error">
52 <span>An error occurred: {{ error.message }}</span>
53 <button @click="reset">Reset error</button>
54 </span>
55 <button @click="addTodo">Create Todo</button>
56</template>
57```
58β
59[//]: # 'Example3'
60[//]: # 'Example11'
61β
62```js
63const queryClient = new QueryClient({
64 defaultOptions: {
65 queries: {
66 gcTime: 24 * 60 * 60 * 1000, // 24 hours
67 },
68 },
69})
70β
71// we need a default mutation function so that paused mutations can resume after a page reload
72queryClient.setMutationDefaults(['todos'], {
73 mutationFn: ({ id, data }) => {
74 return api.updateTodo(id, data)
75 },
76})
77β
78const vueQueryOptions: VueQueryPluginOptions = {
79 queryClient,
80 clientPersister: (queryClient) => {
81 return persistQueryClient({
82 queryClient,
83 persister: createAsyncStoragePersister({ storage: localStorage }),
84 })
85 },
86 clientPersisterOnSuccess: (queryClient) => {
87 queryClient.resumePausedMutations()
88 },
89}
90β
91createApp(App).use(VueQueryPlugin, vueQueryOptions).mount('#app')
92```
93β
94[//]: # 'Example11'
95[//]: # 'OfflineExampleLink'
96β
97We also have an extensive [offline example](../examples/offline-vue-router) that covers both queries and mutations.
98β
99[//]: # 'OfflineExampleLink'
100[//]: # 'Materials'
101[//]: # 'Materials'