InView
This is a component that uses IntersectionObserver to check whether something is within the viewport.
import { PrefetchQuery } from '@suspensive/react-query'
import { InView } from '@suspensive/react-dom'
const PostsPage = ({ posts }: { posts: Post[] }) => (
<div>
<h1>Posts</h1>
{posts.map((post) => (
<InView>
{({ ref, isInView }) => (
<div ref={ref}>
{isInView ? (
// 🚫 Due to the limitations of React hooks, we cannot use usePrefetchQuery here
// usePrefetchQuery({
// queryKey: ['posts', post.id, 'comments'],
// queryFn: () => getPostComments(post.id),
// })
// ✅ Before entering the Post Comments page, we can call usePrefetchQuery for each post comments query.
<PrefetchQuery
queryKey={['posts', post.id, 'comments']}
queryFn={() => getPostComments(post.id)}
/>
) : null}
<h2>{post.title}</h2>
<p>{post.description}</p>
<Link to={`/posts/${post.id}/comments`}>See comments</Link>
</div>
)}
</InView>
))}
</div>
)props.onInView, onInViewEnd
onInView is a callback function that is called when the element enters the viewport.
onInViewEnd is a callback function that is called when the element leaves the viewport.
props.threshold
threshold sets the threshold for the IntersectionObserver.
props.triggerOnce
triggerOnce is a boolean that determines whether the callback should be triggered only once. If set to true, the callback will only be triggered once when the element enters the viewport.
props.skip
skip is a boolean that determines whether the callback should be skipped. If set to true, the callback will not be triggered.
props.delay
delay is a number that sets the delay for the IntersectionObserver. It is used to debounce the callback.
Last updated on