PrefetchQuery
A component that allows you to use usePrefetchQuery in JSX, avoiding the limitations of React hooks.
import { PrefetchQuery, useSuspenseQuery, queryOptions } from '@suspensive/react-query'
import { InView } from '@suspensive/react-dom'
import { useQuery } from '@tanstack/react-query'
const PostsPage = () => {
const { data: posts } = useSuspenseQuery(query.posts())
return posts.map(({ id, title, description }) => (
<InView>
{({ ref, isInView }) => {
return (
<>
{isInView ? (
// 🚫 We can not invoke usePrefetchQuery like below because of React Hook rules
// usePrefetchQuery(query.post(post.id))
// ✅ We can invoke usePrefetch for each post query before entering Post page
<PrefetchQuery {...query.post(id)} />
) : null}
<Link to={`/post/${id}`}>
<div ref={ref}>
<h2>{title}</h2>
<p>{description}</p>
</div>
</Link>
</>
)
}}
</InView>
))
}
const query = {
posts: () =>
queryOptions({
queryKey: ['posts'],
queryFn: () => getPosts(),
}),
post: (postId) =>
queryOptions({
queryKey: ['posts', postId],
queryFn: () => getPost(postId),
}),
}