1 import { HttpTypes } from "@medusajs/types"
2 import {
3 OnChangeFn,
4 PaginationState,
5 getCoreRowModel,
6 getPaginationRowModel,
7 useReactTable,
8 } from "@tanstack/react-table"
9 import { useEffect, useMemo, useState } from "react"
10 import { useSearchParams } from "react-router-dom"
11
12 type UseTaxRegionTableProps = {
13 data?: HttpTypes.AdminTaxRegion[]
14 count?: number
15 pageSize?: number
16 prefix?: string
17 }
18
19 export const useTaxRegionTable = ({
20 data = [],
21 count = 0,
22 pageSize: _pageSize = 10,
23 prefix,
24 }: UseTaxRegionTableProps) => {
25 const [searchParams, setSearchParams] = useSearchParams()
26 const offsetKey = `${prefix ? `${prefix}_` : ""}offset`
27 const offset = searchParams.get(offsetKey)
28
29 const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({
30 pageIndex: offset ? Math.ceil(Number(offset) / _pageSize) : 0,
31 pageSize: _pageSize,
32 })
33 const pagination = useMemo(
34 () => ({
35 pageIndex,
36 pageSize,
37 }),
38 [pageIndex, pageSize]
39 )
40
41 useEffect(() => {
42 const index = offset ? Math.ceil(Number(offset) / _pageSize) : 0
43
44 if (index === pageIndex) {
45 return
46 }
47
48 setPagination((prev) => ({
49 ...prev,
50 pageIndex: index,
51 }))
52 }, [offset, _pageSize, pageIndex])
53
54 const onPaginationChange = (
55 updater: (old: PaginationState) => PaginationState
56 ) => {
57 const state = updater(pagination)
58 const { pageIndex, pageSize } = state
59
60 setSearchParams((prev) => {
61 if (!pageIndex) {
62 prev.delete(offsetKey)
63 return prev
64 }
65
66 const newSearch = new URLSearchParams(prev)
67 newSearch.set(offsetKey, String(pageIndex * pageSize))
68
69 return newSearch
70 })
71
72 setPagination(state)
73 return state
74 }
75
76 const table = useReactTable({
77 data,
78 columns: [], // We don't actually want to render any columns
79 pageCount: Math.ceil(count / pageSize),
80 state: {
81 pagination,
82 },
83 getCoreRowModel: getCoreRowModel(),
84 onPaginationChange: onPaginationChange as OnChangeFn<PaginationState>,
85 getPaginationRowModel: getPaginationRowModel(),
86 manualPagination: true,
87 })
88
89 return {
90 table,
91 }
92 }