Skip to content

Commit

Permalink
feat: add useItemPagination composable
Browse files Browse the repository at this point in the history
  • Loading branch information
andre8244 committed Apr 10, 2024
1 parent 5ac2f03 commit a66b417
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
44 changes: 44 additions & 0 deletions src/composables/useItemPagination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useOffsetPagination } from '@vueuse/core'
import { computed, toValue, type MaybeRefOrGetter } from 'vue'

export type ItemPaginationSettings = {
itemsPerPage: number
onPageChange?: () => void
}

/**
* Composable that provides pagination functionality for an array of items,
* returning the paginated items based on the current page.
* @param {MaybeRefOrGetter<T[]>} items - The array of items to paginate.
* @param {ItemPaginationSettings} settings - The pagination settings, including the number of items per
* page and an optional onPageChange callback.
*
* @example
* const { currentPage, pageCount, paginatedItems, prev, next } = useItemPagination(items, { itemsPerPage: 10 });
*/
export function useItemPagination<T>(
items: MaybeRefOrGetter<T[]>,
settings: ItemPaginationSettings
) {
const { currentPage, pageCount, prev, next } = useOffsetPagination({
page: 1,
pageSize: settings.itemsPerPage,
total: () => toValue(items).length,
onPageChange: settings.onPageChange
})

const paginatedItems = computed(() => {
const start = (currentPage.value - 1) * settings.itemsPerPage
const end = start + settings.itemsPerPage
const itemsArray = toValue(items)
return itemsArray.slice(start, end)
})

return {
currentPage,
pageCount,
paginatedItems,
prev,
next
}
}
3 changes: 3 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,6 @@ export {
savePreference,
getPreference
} from '@/lib/storage'

// composables export
export { useItemPagination } from '@/composables/useItemPagination'

0 comments on commit a66b417

Please sign in to comment.