autodoload
This commit is contained in:
parent
8cd565c647
commit
62afad71d3
6 changed files with 144 additions and 88 deletions
|
@ -1,9 +1,10 @@
|
|||
import { Post } from '../model/posts/posts.ts'
|
||||
import PostsFeed from '../components/PostsFeed.tsx'
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import PostsList from '../components/PostsList.tsx'
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import './FeedView.css'
|
||||
import { useIntersectionLoad } from '../hooks/useIntersectionLoad.ts'
|
||||
|
||||
const PageSize = 10
|
||||
const PageSize = 20
|
||||
|
||||
interface FeedViewProps {
|
||||
loadPosts: (cursor: string | null, amount: number) => Promise<Post[]>
|
||||
|
@ -26,12 +27,10 @@ export default function FeedView({ loadPosts }: FeedViewProps) {
|
|||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const delay = new Promise((resolve) => setTimeout(resolve, 500)) // minimum delay
|
||||
const delay = new Promise((resolve) => setTimeout(resolve, 500))
|
||||
const pagePromise = loadPosts(cursor.current, PageSize)
|
||||
|
||||
const [page] = await Promise.all([pagePromise, delay]) // wait for both
|
||||
|
||||
if (page.length < PageSize) setHasMore(false)
|
||||
const [page] = await Promise.all([pagePromise, delay])
|
||||
setHasMore(page.length >= PageSize)
|
||||
cursor.current = page.at(-1)?.postId ?? null
|
||||
setPages((prev) => [...prev, page])
|
||||
} finally {
|
||||
|
@ -40,47 +39,11 @@ export default function FeedView({ loadPosts }: FeedViewProps) {
|
|||
}
|
||||
}, [loadPosts, hasMore])
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
const entry = entries[0]
|
||||
if (entry.isIntersecting) {
|
||||
loadNextPage()
|
||||
}
|
||||
},
|
||||
{
|
||||
root: null,
|
||||
rootMargin: '100px',
|
||||
threshold: 0.1,
|
||||
},
|
||||
)
|
||||
|
||||
const sentinel = sentinelRef.current
|
||||
if (sentinel) observer.observe(sentinel)
|
||||
return () => {
|
||||
if (sentinel) observer.unobserve(sentinel)
|
||||
}
|
||||
}, [loadNextPage])
|
||||
|
||||
// Ensure content fills viewport after initial render
|
||||
useEffect(() => {
|
||||
const checkContentHeight = async () => {
|
||||
while (
|
||||
document.documentElement.scrollHeight <= window.innerHeight &&
|
||||
hasMore &&
|
||||
!loading.current
|
||||
) {
|
||||
await loadNextPage()
|
||||
}
|
||||
}
|
||||
|
||||
checkContentHeight()
|
||||
}, [posts.length, loadNextPage, hasMore])
|
||||
|
||||
useIntersectionLoad(loadNextPage, sentinelRef)
|
||||
return (
|
||||
<main className="w-full max-w-full px-12 py-6">
|
||||
<div className="col-start-1">
|
||||
<PostsFeed posts={posts} />
|
||||
<PostsList posts={posts} />
|
||||
{isLoading && (
|
||||
<div className="w-full flex justify-center py-4">
|
||||
<Spinner />
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue