All files / hooks/src/use-pagination-hook index.ts

100% Statements 24/24
100% Branches 11/11
100% Functions 7/7
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55              1x               1x   1x 19x 1x     18x   18x 8x 4x       18x 2x 2x     18x 2x 2x     18x   18x 18x 14x   4x       18x     19x  
/**
 * Copyright (c) 2021-present, Matti Bar-Zeev.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
 
import {useEffect, useRef, useState} from 'react';
 
type UsePaginationProps = {
    totalPages: number;
    initialCursor?: number;
    onChange?: (value: number) => void;
};
 
export const NO_TOTAL_PAGES_ERROR = 'The UsePagination hook must receive a totalPages argument for it to work';
 
const usePagination = ({totalPages, initialCursor = 0, onChange}: UsePaginationProps) => {
    if (!totalPages) {
        throw new Error(NO_TOTAL_PAGES_ERROR);
    }
 
    const [cursor, setInternalCursor] = useState(initialCursor);
 
    const setCursor = (newCursor: number) => {
        if (newCursor >= 0 && newCursor < totalPages) {
            setInternalCursor(newCursor);
        }
    };
 
    const goNext = () => {
        const nextCursor = cursor + 1;
        setCursor(nextCursor);
    };
 
    const goPrev = () => {
        const prevCursor = cursor - 1;
        setCursor(prevCursor);
    };
 
    const isHookInitializing = useRef(true);
 
    useEffect(() => {
        if (isHookInitializing.current) {
            isHookInitializing.current = false;
        } else {
            onChange?.(cursor);
        }
    }, [cursor]);
 
    return {totalPages, cursor, goNext, goPrev, setCursor};
};
 
export default usePagination;