Query Functions
Query Functions๋ ๋ง ๊ทธ๋๋ก ์ด๋ค ํจ์๋ ๋ ์ ์๋ค. (promise์ ๋ฐํํ๋) ๋ฐํ๋ promise์ ๋ฐ์ดํฐ๋ฅผ ํด๊ฒฐํ๊ฑฐ๋ ์ค๋ฅ๋ฅผ ๋์ ธ์ผ ํ๋ค.
๋ค์์ ์ฝ๋๋ค์ ์ ํจํ ์ฟผ๋ฆฌ ํจ์ ๊ตฌ์ฑ์ด๋ค.
1useQuery({ queryKey: ['todos'], queryFn: fetchAllTodos })2useQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodoById(todoId) })3useQuery({4queryKey: ['todos', todoId],5queryFn: async () => {6const data = await fetchTodoById(todoId)7return data8},9})10useQuery({11queryKey: ['todos', todoId],12queryFn: ({ queryKey }) => fetchTodoById(queryKey[1]),13})
1. ์๋ฌ ์ฒ๋ฆฌ(handle) ๋ฐ ๋์ง๊ธฐ(throw)
TanStack Query๊ฐ query์ ์๋ฌ๊ฐ ์์์ ํ์ธํ๊ธฐ ์ํด์๋, query ํจ์๊ฐ ๋ฐํ๋ promise๋ฅผ throwํ๊ฑฐ๋ ๋ฐํํด์ผ ํ๋ค.
query ํจ์์์ ๋์ ธ์ง ์ด๋ ํ ์๋ฌ๋ query์ error ์ํ๋ฅผ ์ ์งํด์ผ ํฉ๋๋ค.
1const { error } = useQuery({2queryKey: ['todos', todoId],3queryFn: async () => {4if (somethingGoesWrong) {5throw new Error('Oh no!')6}7if (somethingElseGoesWrong) {8return Promise.reject(new Error('Oh no!'))9}1011return data12},13})
2. ๊ธฐ๋ณธ์ (default)์ผ๋ก ๋ฐ์(throw)ํ์ง ์๋ ๊ธฐํ ํด๋ผ์ด์ธํธ์ fetch ์ฌ์ฉ๋ฒ
axios๋ graphql-request์ ๊ฐ์ ๋๋ถ๋ถ์ ์ ํธ๋ฆฌํฐ๋ ์คํจํ HTTP ํธ์ถ์ ๋ํด ์๋์ผ๋ก ์ค๋ฅ๋ฅผ ๋์ง์ง๋ง, fetch์ ๊ฐ์ ์ผ๋ถ ์ ํธ๋ฆฌํฐ๋ ๊ธฐ๋ณธ์ ์ผ๋ก ์ค๋ฅ๋ฅผ ๋์ง์ง ์๋๋ค.
1useQuery({2queryKey: ['todos', todoId],3queryFn: async () => {4const response = await fetch('/todos/' + todoId)5if (!response.ok) {6throw new Error('Network response was not ok')7}8return response.json()9},10})
3. Query Function Variables(๋ณ์)
Query keys๋ ๊ฐ์ ธ์ค๋ ๋ฐ์ดํฐ๋ฅผ ๊ณ ์ ํ๊ฒ ์๋ณํ๊ธฐ ์ํ ๊ฒ์ผ ๋ฟ๋ง ์๋๋ผ, QueryFunctionContext์ ์ผ๋ถ๋ก Query Function์ ์๋ง๊ฒ ์ ๋ฌ๋ฉ๋๋ค. ํญ์ ํ์ํ ๊ฒ์ ์๋์ง๋ง, ๋๊ฐ ํ์ํ๋ค๋ฉด, ๋์ query function๋ค์ ์ถ์ถํ ์๋ ์๋ค.
1function Todos({ status, page }) {2const result = useQuery({3queryKey: ['todos', { status, page }],4queryFn: fetchTodoList,5})6}78// Access the key, status and page variables in your query function!9function fetchTodoList({ queryKey }) {10const [_key, { status, page }] = queryKey11return new Promise()12}
4. QueryFunctionContext
QueryFunctionContext๋ ๊ฐ Query Function์ ์ ๋ฌ๋๋ ๊ฐ์ฒด์ ๋๋ค. ์ด๋ ๋ค์๊ณผ ๊ฐ์ด ๊ตฌ์ฑ๋ฉ๋๋ค:
queryKey: QueryKey: Query Keyssignal?: AbortSignal- TanStack Query์์ ์ ๊ณตํ๋ AbortSignal instance
- Query Cancellation์ ์ฌ์ฉ ๊ฐ๋ฅ
meta: Record<string, unknown> | undefined- ์ฟผ๋ฆฌ์ ๋ํ ์ถ๊ฐ ์ ๋ณด๋ก ์ฑ์ธ ์ ์๋ ์ ํ์ ํ๋
๋ํ Infinite Queries๋ ๋ค์ ์ต์ ์ ์ ๋ฌํฉ๋๋ค.
pageParam: TPageParam- ํ์ฌ ํ์ด์ง๋ฅผ ๊ฐ์ ธ์ค๋ ๋ฐ ์ฌ์ฉ๋๋ page ๋งค๊ฐ ๋ณ์
direction: 'forward' | 'backward'- ํ์ฌ ํ์ด์ง ๊ฐ์ ธ์ค๊ธฐ์ ๋ฐฉํฅ