Skip to content

Commit

Permalink
Implement infinite scroll in UsersView with InView
Browse files Browse the repository at this point in the history
  • Loading branch information
fwcd committed Oct 7, 2024
1 parent 198ec6e commit fc357e0
Showing 1 changed file with 14 additions and 19 deletions.
33 changes: 14 additions & 19 deletions src/screens/home/admin/UsersView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,27 +15,22 @@ import {
TableRow,
Tooltip,
} from '@nextui-org/react';
import { useInfiniteScroll } from '@nextui-org/use-infinite-scroll';
import { useAsyncList } from '@react-stately/data';
import {
IconEye,
IconPencil,
IconTrash,
IconUserPlus,
} from '@tabler/icons-react';
import {
MutableRefObject,
useCallback,
useContext,
useEffect,
useState,
} from 'react';
import { useCallback, useContext, useEffect, useState } from 'react';
import { InView } from 'react-intersection-observer';
import { SortDescriptor } from 'react-stately';

export function UsersView() {
const auth = useContext(AuthContext);

const [isLoading, setLoading] = useState(false);
const [needsMore, setNeedsMore] = useState(false);
const [hasMore, setHasMore] = useState(false);

const sortList = useCallback(
Expand Down Expand Up @@ -86,17 +81,11 @@ export function UsersView() {
},
});

const [loaderRef, scrollerRef] = useInfiniteScroll({
hasMore,
onLoadMore: users.loadMore,
});

// A hack to let us use infinite scrolling without a wrapper. Pretty sure you
// are not supposed to (ab)use React refs like this, it seems to work well
// enough in practice though.
useEffect(() => {
(scrollerRef as MutableRefObject<HTMLElement>).current = document.body;
}, [scrollerRef]);
if (needsMore) {
users.loadMore();
}
}, [users, needsMore]);

const [userModal, setUserModal] = useState<{
id: number;
Expand Down Expand Up @@ -132,7 +121,13 @@ export function UsersView() {
isHeaderSticky
sortDescriptor={users.sortDescriptor}
onSortChange={users.sort}
bottomContent={hasMore ? <Spinner ref={loaderRef} /> : null}
bottomContent={
hasMore ? (
<InView onChange={setNeedsMore}>
{({ inView, ref }) => <Spinner ref={ref} />}
</InView>
) : null
}
>
<TableHeader>
<TableColumn key="id" allowsSorting>
Expand Down

0 comments on commit fc357e0

Please sign in to comment.