1- import { useEffect , useMemo , useState } from 'react' ;
1+ import { useCallback , useEffect , useMemo , useState } from 'react' ;
22import { useSearchParams } from 'react-router' ;
33
44import { PAGE_CONTAINER_ID } from 'constants/layout' ;
@@ -9,31 +9,45 @@ type PaginationProps = {
99 itemsCount : number ;
1010 onChange : ( newPageIndex : number ) => void ;
1111 itemsPerPageCount ?: number ;
12+ // Search param key holding the active page, so several tables can paginate independently
13+ paramKey ?: string ;
1214} ;
1315
1416const PAGES_TO_SHOW_COUNT = 4 ;
1517
16- export function usePagination ( { itemsCount, onChange, itemsPerPageCount = 10 } : PaginationProps ) {
18+ export function usePagination ( {
19+ itemsCount,
20+ onChange,
21+ itemsPerPageCount = 10 ,
22+ paramKey = PAGE_PARAM_KEY ,
23+ } : PaginationProps ) {
1724 const { t } = useTranslation ( ) ;
1825 const scrollElem = document . getElementById ( PAGE_CONTAINER_ID ) ;
1926
2027 const [ searchParams , setSearchParams ] = useSearchParams ( ) ;
2128
29+ const setPageParam = useCallback (
30+ ( page : string ) =>
31+ setSearchParams ( currentSearchParams => ( {
32+ ...Object . fromEntries ( currentSearchParams ) ,
33+ [ paramKey ] : page ,
34+ } ) ) ,
35+ [ setSearchParams , paramKey ] ,
36+ ) ;
37+
2238 const [ urlPageParam , activePageIndex ] = useMemo ( ( ) => {
23- const pageParam = searchParams . get ( PAGE_PARAM_KEY ) ;
39+ const pageParam = searchParams . get ( paramKey ) ;
2440 const pageIndex = pageParam ? + pageParam - 1 : 0 ;
2541
2642 return [ pageParam , pageIndex ] ;
27- } , [ searchParams ] ) ;
43+ } , [ searchParams , paramKey ] ) ;
2844
2945 // Automatically set default page param if none was set
3046 useEffect ( ( ) => {
3147 if ( urlPageParam === undefined ) {
32- setSearchParams ( {
33- [ PAGE_PARAM_KEY ] : '1' ,
34- } ) ;
48+ setPageParam ( '1' ) ;
3549 }
36- } , [ urlPageParam , setSearchParams ] ) ;
50+ } , [ urlPageParam , setPageParam ] ) ;
3751
3852 const [ pagesCount , setPagesCount ] = useState ( 0 ) ;
3953
@@ -68,9 +82,7 @@ export function usePagination({ itemsCount, onChange, itemsPerPageCount = 10 }:
6882 : activePageIndex + halfOfPagesCount ;
6983
7084 const handlePageChange = ( pageIndex : number ) => {
71- setSearchParams ( {
72- [ PAGE_PARAM_KEY ] : pageIndex . toString ( ) ,
73- } ) ;
85+ setPageParam ( pageIndex . toString ( ) ) ;
7486
7587 onChange ( pageIndex ) ;
7688
0 commit comments