Last active
January 11, 2023 19:19
-
-
Save maiconrs95/91f176526f9a688f900cb65e132990c3 to your computer and use it in GitHub Desktop.
Custom React hook to paginate array list
This file contains 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
import * as React from 'react'; | |
export const paginateArray = (arr = [], size = 10) => | |
arr.reduce((acc, val, i) => { | |
const idx = Math.floor(i / size); | |
const page = acc[idx] || (acc[idx] = []); | |
page.push(val); | |
return acc; | |
}, []); | |
type Result<T> = { | |
data: Array<T>; | |
total: number; | |
page: number; | |
next: () => void; | |
prev: () => void; | |
}; | |
const increase = | |
(total = 0) => | |
(current = 0) => { | |
if (total === current) return current; | |
return (current += 1); | |
}; | |
const decrease = (current: number) => { | |
if (current === 1) return current; | |
return (current -= 1); | |
}; | |
function usePaginatedList<T = never>(arr: Array<T> = [], size = 1): Result<T> { | |
const PAGINATED_ARRAY = paginateArray(arr, size); | |
const total = PAGINATED_ARRAY.length; | |
const [page, setPage] = React.useState(1); | |
const next = React.useCallback(() => { | |
setPage(increase(total)); | |
}, [total]); | |
const prev = React.useCallback(() => { | |
setPage(decrease); | |
}, []); | |
return { | |
data: PAGINATED_ARRAY.slice(0, page).reduce((accumulator, current) => { | |
return accumulator.concat(current); | |
}, []), | |
total, | |
page, | |
next, | |
prev, | |
}; | |
} | |
export default usePaginatedList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment