Skip to content

usePagination

Creates reusable pagination primitives without assuming how data is loaded. Use it when multiple components need the same page, page-size, total, and limits behavior, whether data is sliced locally or fetched from a server.

The composable keeps state deliberately simple: setters only assign values and do not clamp pages, reset page numbers, or trigger side effects. That makes it predictable, but callers should handle validation when needed.

Importing

ts
import { usePagination } from '@almighty-shogun/vue-utils'

Usage

ts
import { watch } from 'vue'
import { usePagination } from '@almighty-shogun/vue-utils'

const { page, perPage, setPage, setPerPage, setTotal } = usePagination(25);

watch([page, perPage], async () => {
    const response = await fetch('/api/users?page=' + page.value + '&limit=' + perPage.value);
    const result = await response.json();

    setTotal(result.total);
});

setPage(2);
setPerPage(50);

Parameters

NameTypeDescription
pageSizenumberInitial perPage value. Defaults to 5.

Returns

NameTypeDescription
limitsRef<number[]>Available page-size options: [5, 10, 25, 50, 100].
pageRef<number>One-based current page. Starts at 1.
perPageRef<number>Current page size. Starts with pageSize.
totalRef<number>Total number of items across all pages. Starts at 0.
setTotal(total)(total: number) => voidUpdates total item count.
setPage(page)(page: number) => voidUpdates the active page.
setPerPage(perPage)(perPage: number) => voidUpdates the active page size.

Type signature

ts
declare function usePagination(pageSize?: number): UsePagination;

type UsePagination = {
    readonly limits: Ref<number[]>;
    readonly page: Ref<number>;
    readonly perPage: Ref<number>;
    readonly total: Ref<number>;

    setTotal(total: number): void;
    setPage(page: number): void;
    setPerPage(perPage: number): void;
};

All packages are released under the MIT License.