implemented infinite loading

This commit is contained in:
Ren Amamiya
2023-02-28 14:53:27 +07:00
parent f4b5764db6
commit 964343ccc8
6 changed files with 122 additions and 121 deletions

View File

@@ -4,14 +4,18 @@ import NewsFeedLayout from '@layouts/newsfeedLayout';
import { DatabaseContext } from '@components/contexts/database';
import { Placeholder } from '@components/note/placeholder';
import { Thread } from '@components/thread';
import { Repost } from '@components/note/repost';
import { Single } from '@components/note/single';
import { JSXElementConstructor, ReactElement, ReactFragment, ReactPortal, Suspense, useContext, useEffect, useRef, useState } from 'react';
import { useCallback } from 'react';
import { JSXElementConstructor, ReactElement, ReactFragment, ReactPortal, useContext, useEffect, useRef, useState } from 'react';
import { Virtuoso } from 'react-virtuoso';
export default function Page() {
const db: any = useContext(DatabaseContext);
const [data, setData] = useState([]);
const limit = useRef(25);
const [data, setData] = useState(() => []);
const limit = useRef(30);
const offset = useRef(0);
useEffect(() => {
const getData = async () => {
@@ -22,12 +26,55 @@ export default function Page() {
getData().catch(console.error);
}, [db]);
const loadMore = useCallback(async () => {
offset.current += limit.current;
// next query
const result = await db.select(`SELECT * FROM cache_notes ORDER BY created_at DESC LIMIT ${limit.current} OFFSET ${offset.current}`);
setData((data) => [...data, ...result]);
}, [db]);
const ItemContent = useCallback(
(index: string | number) => {
const event = data[index];
if (event.content.includes('#[0]') && event.tags[0][0] == 'e') {
// type: repost
return <Repost root={event.tags} user={event.pubkey} />;
} else {
// type: default
return <Single event={event} />;
}
},
[data]
);
const computeItemKey = useCallback(
(index: string | number) => {
return data[index].id;
},
[data]
);
return (
<div className="h-full w-full">
<Suspense fallback={<Placeholder />}>
<Thread data={data} />
</Suspense>
</div>
<Virtuoso
data={data}
itemContent={ItemContent}
components={{
EmptyPlaceholder: () => <Placeholder />,
ScrollSeekPlaceholder: () => <Placeholder />,
}}
computeItemKey={computeItemKey}
scrollSeekConfiguration={{
enter: (velocity) => Math.abs(velocity) > 800,
exit: (velocity) => Math.abs(velocity) < 500,
}}
endReached={loadMore}
overscan={800}
increaseViewportBy={1000}
className="scrollbar-hide relative h-full w-full rounded-lg"
style={{
contain: 'strict',
}}
/>
);
}