usePageLinks.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. import {useMemo} from 'react';
  2. import * as qs from 'query-string';
  3. import {useLocation} from 'sentry/utils/useLocation';
  4. const RESULTS_PER_PAGE = 50;
  5. export function usePageLinks(
  6. data: any[],
  7. cursor: number,
  8. resultsPerPage = RESULTS_PER_PAGE
  9. ) {
  10. const location = useLocation();
  11. const pageLinks = useMemo(() => {
  12. const prevResults = cursor >= resultsPerPage ? 'true' : 'false';
  13. const prevCursor = cursor >= resultsPerPage ? cursor - resultsPerPage : 0;
  14. const prevQuery = {...location.query, cursor: prevCursor};
  15. const prevHref = `${location.pathname}${qs.stringify(prevQuery)}`;
  16. const prev = `<${prevHref}>; rel="previous"; results="${prevResults}"; cursor="${prevCursor}"`;
  17. const nextResults = cursor + resultsPerPage < data.length ? 'true' : 'false';
  18. const nextCursor =
  19. cursor + resultsPerPage < data.length ? cursor + resultsPerPage : 0;
  20. const nextQuery = {...location.query, cursor: nextCursor};
  21. const nextHref = `${location.pathname}${qs.stringify(nextQuery)}`;
  22. const next = `<${nextHref}>; rel="next"; results="${nextResults}"; cursor="${nextCursor}"`;
  23. return `${prev},${next}`;
  24. }, [cursor, location, data, resultsPerPage]);
  25. return pageLinks;
  26. }