Last active
August 5, 2021 17:40
-
-
Save ChlorUpload/c945a1126f08bad7c6bf97a13ab88755 to your computer and use it in GitHub Desktop.
pagination
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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