All files / utils usePageSize.js

100% Statements 11/11
100% Branches 4/4
100% Functions 3/3
100% Lines 11/11

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                      614x 186x 186x 66x   120x 120x     614x   614x 10x 10x     614x    
import { useState } from "react";
 
// Reusable hook that manages a page size value, persisting the selection to
// localStorage under `storageKey` so that it is remembered across visits to
// the same table. If the stored value is missing or not one of `options`,
// `defaultPageSize` is used (and localStorage is updated to match).
export default function usePageSize({
  storageKey,
  options = [20, 50, 100, 200, 500],
  defaultPageSize = 20,
}) {
  const getInitialPageSize = () => {
    const storedValue = parseInt(localStorage.getItem(storageKey), 10);
    if (options.includes(storedValue)) {
      return storedValue;
    }
    localStorage.setItem(storageKey, defaultPageSize);
    return defaultPageSize;
  };
 
  const [pageSize, setPageSize] = useState(getInitialPageSize);
 
  const handlePageSizeChange = (newPageSize) => {
    setPageSize(newPageSize);
    localStorage.setItem(storageKey, newPageSize);
  };
 
  return [pageSize, handlePageSizeChange];
}