최근 30분간 동시 방문자 수를 표시합니다. (~)
최고 동시 방문자 수 -
어제: 0명 / 오늘: 0명
Vue에서 TanStack Query를 사용할 때 반환 데이터를 반응형으로 처리하려면, useQuery 함수의 옵션으로 계산된 데이터 참조(ComputedRef)를 전달합니다.
그러면 쿼리 키(queryKey)나 활성화(enabled) 같은 쿼리 옵션의 반응성도 감지됩니다.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859<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('') // input 요소와 연결해 지속적으로 변경 const searchText = ref('') // 검색할 때만 변경 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, // 1시간 캐시 placeholderData: prev => prev, // 이전 데이터를 대기 데이터로 사용(깜빡임 방지) enabled: !!searchText.value // 검색어가 없으면 실행하지 않음 } satisfies UseQueryOptions<Movies> }) console.log(queryOptions) // ComputedRef console.log(queryOptions.value) // 쿼리 옵션 값 const queryClient = useQueryClient() const { data, isFetching } = useQuery<Movie[]>(queryOptions) // ComputedRef 객체를 전달 async function fetchMovies() { searchText.value = inputText.value // 입력된 문자를 검색어로 반영 if (!searchText.value.trim()) return // fetchQuery는 캐시된 데이터를 사용하거나 없으면 새 데이터를 가져옴! await queryClient.fetchQuery(queryOptions) // ComputedRef 객체를 전달 } </script> <template> <div> <input v-model="inputText" @keydown.enter="fetchMovies" /> <button @click="fetchMovies">검색</button> </div> {{ isFetching ? '로딩중...' : '' }} <ul> <li v-for="movie in data" :key="movie.imdbID"> {{ movie.Title }} ({{ movie.Year }}) </li> </ul> <RouterView /> </template>