infiniteQueryOptions
infiniteQueryOptions
๋ Infinite Query์์ queryOptions๋ฅผ ํ์ฉํ ์ ์๋๋ก ๋์์ค๋๋ค. ์ด๋ queryOptions
๊ฐ ์ฌ์ฉ๋๋ ์ด์ ์ ์ ์ฌํ ์ฅ์ ์ ์ ๊ณตํฉ๋๋ค.
import { infiniteQueryOptions, useSuspenseInfiniteQuery, SuspenseInfiniteQuery } from '@suspensive/react-query'
import { useInfiniteQuery, useQueryClient } from '@tanstack/react-query'
const postsInfiniteQueryOptions = (page) =>
infiniteQueryOptions({
queryKey: ['posts', page] as const,
queryFn: ({
queryKey: [, page], // queryKey๋ฅผ ํ์ฉํ ์ ์์ต๋๋ค.
}) => fetch(`https://example.com/posts?page=${page}`).then(res => res.json()),
getNextPageParam: (lastPage) => lastPage.nextPage ?? false,
})
// ์ปค์คํ
์ฟผ๋ฆฌ ํ
์ ๋ง๋ค ํ์๊ฐ ์์ต๋๋ค.
// useInfiniteQuery, useSuspenseInfiniteQuery, SuspenseInfiniteQuery์์ ์ง์ infiniteQueryOptions๋ฅผ ํ์ฉํ ์ ์์ต๋๋ค.
const postsQuery = useInfiniteQuery(postsInfiniteQueryOptions(1))
const { data: posts, fetchNextPage, hasNextPage } = useSuspenseInfiniteQuery({
...postsInfiniteQueryOptions(1),
refetchInterval: 2000, // ์ฌ์ฉ์ฒ์์ ํ์ฅ์ฑ์ ๋ช
ํํ ํํ๋ฉ๋๋ค.
})
const Example = () => (
<SuspenseInfiniteQuery {...postsInfiniteQueryOptions(1)}>
{({ data, fetchNextPage, hasNextPage }) => (
<div>
{data.pages.map((page, index) => (
<div key={index}>
{page.posts.map(post => (
<div key={post.id}>{post.title}</div>
))}
</div>
))}
<button onClick={() => fetchNextPage()} disabled={!hasNextPage}>
Load More
</button>
</div>
)}
</SuspenseInfiniteQuery>
)
// queryClient์ ๋ฉ์๋์์ queryKey์ queryFn์ ์ฝ๊ฒ ํ์ฉํ ์ ์์ต๋๋ค.
const queryClient = useQueryClient()
queryClient.refetchQueries(postsInfiniteQueryOptions(1))
queryClient.prefetchQuery(postsInfiniteQueryOptions(1))
queryClient.invalidateQueries(postsInfiniteQueryOptions(1))
queryClient.fetchQuery(postsInfiniteQueryOptions(1))
queryClient.resetQueries(postsInfiniteQueryOptions(1))
queryClient.cancelQueries(postsInfiniteQueryOptions(1))