Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

mutations.md

101 lines2.2 KB

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' })
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' })
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 },
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'