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

mutations.md

97 lines2.1 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>
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-else-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 client = new QueryClient({
64 defaultOptions: {
65 queries: {
66 gcTime: 1000 * 60 * 60 * 24, // 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({
73 mutationKey: ['todos'],
74 mutationFn: ({ id, data }) => {
75 return api.updateTodo(id, data)
76 },
77})
78​
79const vueQueryOptions: VueQueryPluginOptions = {
80 queryClient: client,
81 clientPersister: (queryClient) => {
82 return persistQueryClient({
83 queryClient,
84 persister: createAsyncStoragePersister({ storage: localStorage }),
85 })
86 },
87 clientPersisterOnSuccess: (queryClient) => {
88 queryClient.resumePausedMutations()
89 },
91​
92createApp(App).use(VueQueryPlugin, vueQueryOptions).mount('#app')
93```
94​
95[//]: # 'Example11'
96[//]: # 'Materials'
97[//]: # 'Materials'