queryOptions
TanStack Query์ ๋ฉ์ธํ ์ด๋ Tkdodo์ TanStack Query v5์ queryOptions ์ค๋ช ์์์์ ์ด interface๊ฐ ํ์ํ ์ด์ ๋ฅผ ์ ์ค๋ช ๋์ด ์์ต๋๋ค. TanStack Query v4์์๋ queryOptions๋ฅผ ํ์ฉํ ์ ์์ต๋๋ค.
- queryKey์ queryFn์ ๋ฌถ์ด์ ์ฒ๋ฆฌํด queryKey๊ด๋ฆฌ๊ฐ ์ฌ์์ง๋๋ค.
- ๋ถํ์ํ ์ปค์คํ
์ฟผ๋ฆฌ ํ
์ ์ ๊ฑฐํ ์ ์์ต๋๋ค. TanStack Query v4์
useQuery
,useQueries
, Suspensive React Query์useSuspenseQuery
,useSuspenseQueries
,SuspenseQuery
์ ๋ชจ๋ ์ง์ ์ฌ์ฉํ ์ ์๊ธฐ ๋๋ฌธ์ ๋๋ค. - TanStack Query v5์๋ ์ด๋ฏธ queryOptions๊ฐ ์ ๊ณต๋๊ณ ์๊ธฐ ๋๋ฌธ์ TanStack Query v4์์ TanStack Query v5๋ก์ ๋ง์ด๊ทธ๋ ์ด์ ์ด ์ฌ์์ง๋๋ค.
import { queryOptions, useSuspenseQuery, useSuspenseQueries, SuspenseQuery } from '@suspensive/react-query'
import { useQuery, useQueries, useQueryClient } from '@tanstack/react-query'
const postQueryOptions = (postId) =>
queryOptions({
queryKey: ['posts', postId] as const,
queryFn: ({
queryKey: [, postId], // queryKey๋ฅผ ํ์ฉํ ์ ์์ต๋๋ค.
}) => fetch(`https://example.com/posts/${postId}`),
})
// ์ปค์คํ
์ฟผ๋ฆฌ ํ
์ ๋ง๋ค ํ์๊ฐ ์์ต๋๋ค.
// useQuery, useQueries, useSuspenseQuery, useSuspenseQueries, SuspenseQuery์์ ์ง์ queryOptions๋ฅผ ํ์ฉํ ์ ์์ต๋๋ค.
const post1Query = useQuery(postQueryOptions(1))
const { data: post1 } = useSuspenseQuery({
...postQueryOptions(1),
refetchInterval: 2000, // ์ฌ์ฉ์ฒ์์ ํ์ฅ์ฑ์ ๋ช
ํํ ํํ๋ฉ๋๋ค.
})
const [post1Query, post2Query] = useQueries({
queries: [postQueryOptions(1), { ...postQueryOptions(2), refetchInterval: 2000 }],
})
const [{ data: post1 }, { data: post2 }] = useSuspenseQueries({
queries: [postQueryOptions(1), { ...postQueryOptions(2), refetchInterval: 2000 }],
})
const Example = () => <SuspenseQuery {...postQueryOptions(1)}>{({ data: post1 }) => <>{post1.text}</>}</SuspenseQuery>
// queryClient์ ๋ฉ์๋์์ queryKey์ queryFn์ ์ฝ๊ฒ ํ์ฉํ ์ ์์ต๋๋ค.
const queryClient = useQueryClient()
queryClient.refetchQueries(postQueryOptions(1))
queryClient.prefetchQuery(postQueryOptions(1))
queryClient.invalidateQueries(postQueryOptions(1))
queryClient.fetchQuery(postQueryOptions(1))
queryClient.resetQueries(postQueryOptions(1))
queryClient.cancelQueries(postQueryOptions(1))