99

Concurrent visitors over the last 30 minutes. (~)

Peak concurrent visitors -
Yesterday: 0 / Today: 0

An Example of Searching and Listing Movies with useQuery in TanStack Vue Query

VueTanStack Query
a year ago
0

When you use TanStack Query in Vue, to handle the returned data reactively, pass a computed data reference (ComputedRef) as the options of the useQuery function.
Then changes in query options such as the query key (queryKey) and enabled are also tracked reactively.

VUE
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<script setup lang="ts"> import { ref, computed } from 'vue' import { useQuery, useQueryClient } from '@tanstack/vue-query' import type { UseQueryOptions } from '@tanstack/vue-query' type Movies = Movie[] interface Movie { imdbID: string Title: string Poster: string Year: string } const inputText = ref('') // Bound to the input element, so it changes continuously const searchText = ref('') // Changes only when you search const queryOptions = computed(() => { return { queryKey: ['movies', searchText.value], queryFn: async () => { const res = await fetch(`https://omdbapi.com?apikey=7035c60c&s=${searchText.value}`) const { Search: movies = [] } = await res.json() return movies as Movies }, staleTime: 1000 * 60 * 60, // Cache for 1 hour placeholderData: prev => prev, // Use the previous data as placeholder data (prevents flickering) enabled: !!searchText.value // Don't run if there's no search text } satisfies UseQueryOptions<Movies> }) console.log(queryOptions) // ComputedRef console.log(queryOptions.value) // Query option values const queryClient = useQueryClient() const { data, isFetching } = useQuery<Movie[]>(queryOptions) // Pass the ComputedRef object async function fetchMovies() { searchText.value = inputText.value // Use the entered text as the search text if (!searchText.value.trim()) return // fetchQuery uses the cached data, or fetches new data if there's none! await queryClient.fetchQuery(queryOptions) // Pass the ComputedRef object } </script> <template> <div> <input v-model="inputText" @keydown.enter="fetchMovies" /> <button @click="fetchMovies">Search</button> </div> {{ isFetching ? 'Loading...' : '' }} <ul> <li v-for="movie in data" :key="movie.imdbID"> {{ movie.Title }} ({{ movie.Year }}) </li> </ul> <RouterView /> </template>