change onscrollend to obeserver implemention

This commit is contained in:
jasinco 2025-06-11 01:19:28 +08:00
parent 2e842cd3e3
commit ec2b8570eb

View file

@ -1,4 +1,4 @@
import React from "react" import React, { useEffect, useRef } from "react"
import { FetchPost, MediaPathTrc, SinglePost_t } from "./api" import { FetchPost, MediaPathTrc, SinglePost_t } from "./api"
import { z } from 'zod/v4' import { z } from 'zod/v4'
import { useInfiniteQuery } from "@tanstack/react-query" import { useInfiniteQuery } from "@tanstack/react-query"
@ -50,9 +50,17 @@ export const Fetch = () => {
return lastPage !== null && lastPage.length > 0 && (lastPage[lastPage.length - 1].id - 1) > 0 ? lastPage[lastPage.length - 1].id - 1 : undefined return lastPage !== null && lastPage.length > 0 && (lastPage[lastPage.length - 1].id - 1) > 0 ? lastPage[lastPage.length - 1].id - 1 : undefined
}, },
}) })
const observer = new IntersectionObserver((ent) => {
if (ent[0].isIntersecting && ent[0].intersectionRatio > 90) {
hasNextPage && !isFetching && fetchNextPage()
}
})
useEffect(() => {
observer.observe(document.getElementById("skeleton")!)
}, [])
return ( return (
<div className="h-dvh w-dvw flex flex-col items-center gap-6 py-8 px-4 overflow-scroll" onScrollEnd={() => hasNextPage && !isFetching && fetchNextPage()}> <div className="h-dvh w-dvw flex flex-col items-center gap-6 py-8 px-4 overflow-scroll">
{status === 'pending' && <p>Loading</p>} {status === 'pending' && <p>Loading</p>}
{status === 'error' && <p>Error: {error.message}</p>} {status === 'error' && <p>Error: {error.message}</p>}
{data && data.pages.map((group, i) => ( {data && data.pages.map((group, i) => (
@ -62,8 +70,8 @@ export const Fetch = () => {
))} ))}
</React.Fragment> </React.Fragment>
))} ))}
{hasNextPage && <div className="w-full max-w-2xl bg-gray-200 rounded-lg shadow-md p-6 flex flex-col gap-4 animate-pulse h-[20dvh]" > <div className={"w-full max-w-2xl bg-gray-200 rounded-lg shadow-md p-6 flex flex-col gap-4 animate-pulse h-[20dvh]" + (hasNextPage ? "" : " hidden")} id="skeleton">
</div>} </div>
{!hasNextPage && <p className="mb-15"></p>} {!hasNextPage && <p className="mb-15"></p>}
</div> </div>
) )