|
| 1 | +<script setup lang="ts"> |
| 2 | +import { ref } from 'vue' |
| 3 | +import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query' |
| 4 | +import { VueQueryDevtools } from '@tanstack/vue-query-devtools' |
| 5 | +import { todosMutations, todosQueries } from './services/todos/queries' |
| 6 | +
|
| 7 | +const queryClient = useQueryClient() |
| 8 | +const intervalMs = ref(1000) |
| 9 | +const value = ref('') |
| 10 | +
|
| 11 | +const { status, data, error, isFetching } = useQuery(() => ({ |
| 12 | + ...todosQueries.list(), |
| 13 | + // Refetch the data every second |
| 14 | + refetchInterval: intervalMs.value, |
| 15 | +})) |
| 16 | +
|
| 17 | +const { mutate: addTodo } = useMutation({ |
| 18 | + ...todosMutations.create(), |
| 19 | + onSuccess: () => |
| 20 | + queryClient.invalidateQueries({ queryKey: todosQueries.all() }), |
| 21 | +}) |
| 22 | +
|
| 23 | +const { mutate: clearTodos } = useMutation({ |
| 24 | + ...todosMutations.deleteAll(), |
| 25 | + onSuccess: () => |
| 26 | + queryClient.invalidateQueries({ queryKey: todosQueries.all() }), |
| 27 | +}) |
| 28 | +
|
| 29 | +const onSubmit = () => { |
| 30 | + addTodo(value.value, { |
| 31 | + onSuccess: () => { |
| 32 | + value.value = '' |
| 33 | + }, |
| 34 | + }) |
| 35 | +} |
| 36 | +</script> |
| 37 | + |
| 38 | +<template> |
| 39 | + <h1 v-if="status === 'pending'">Loading...</h1> |
| 40 | + <span v-else-if="status === 'error'">Error: {{ error?.message }}</span> |
| 41 | + <div v-else> |
| 42 | + <h1>Auto Refetch with refetchInterval set to {{ intervalMs }}ms</h1> |
| 43 | + <p> |
| 44 | + This example is best experienced on your own machine, where you can open |
| 45 | + multiple tabs to the same localhost server and see your changes propagate |
| 46 | + between the two. |
| 47 | + </p> |
| 48 | + <label> |
| 49 | + Query Interval speed (ms): |
| 50 | + <input v-model.number="intervalMs" type="number" step="100" /> |
| 51 | + {{ ' ' }} |
| 52 | + <span |
| 53 | + :style="{ |
| 54 | + display: 'inline-block', |
| 55 | + marginLeft: '.5rem', |
| 56 | + width: '10px', |
| 57 | + height: '10px', |
| 58 | + background: isFetching ? 'green' : 'transparent', |
| 59 | + transition: !isFetching ? 'all .3s ease' : 'none', |
| 60 | + borderRadius: '100%', |
| 61 | + transform: 'scale(2)', |
| 62 | + }" |
| 63 | + /> |
| 64 | + </label> |
| 65 | + <h2>Todo List</h2> |
| 66 | + <form @submit.prevent="onSubmit"> |
| 67 | + <input v-model="value" placeholder="enter something" /> |
| 68 | + </form> |
| 69 | + <ul> |
| 70 | + <li v-for="item in data" :key="item">{{ item }}</li> |
| 71 | + </ul> |
| 72 | + <div> |
| 73 | + <button @click="clearTodos()">Clear All</button> |
| 74 | + </div> |
| 75 | + <VueQueryDevtools initialIsOpen /> |
| 76 | + </div> |
| 77 | +</template> |
0 commit comments