Skip to content

Instantly share code, notes, and snippets.

@ChlorUpload
Last active August 5, 2021 17:40
Show Gist options
  • Save ChlorUpload/c945a1126f08bad7c6bf97a13ab88755 to your computer and use it in GitHub Desktop.
Save ChlorUpload/c945a1126f08bad7c6bf97a13ab88755 to your computer and use it in GitHub Desktop.
pagination
type PaginationRes<T> = {
length: number | null;
partialData: T[] | null;
pageInd: number;
setPageInd: (pageInd: number) => void;
refreshData: () => void;
};
function usePagination<T>(
getLength: () => Promise<number>,
getPartialData: (startIdx: number, endIdx: number) => Promise<T[] | null>,
partitionLength: number = 10,
): PaginationRes<T> {
const [length, setLength] = useState<number | null>(null);
const [partialData, setpartialData] = useState<T[] | null>(null);
const [pageInd, setPageInd] = useState(0);
const refreshData = async () => {
const len = await getLength();
if (len !== null) setLength(len);
};
const refresh = async () => {
if (length !== null) {
let startIdx = pageInd * partitionLength;
let endIdx = pageInd * partitionLength + partitionLength;
if (endIdx > length) endIdx = length;
const result = await getPartialData(startIdx, endIdx);
if (result !== null) {
setpartialData(result);
}
}
};
useEffect(() => {
refresh();
}, [length, partitionLength, pageInd]);
return { length, partialData, pageInd, setPageInd, refreshData };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment