diff --git a/components/txs-table/index.tsx b/components/txs-table/index.tsx index 4aa5013..93ee97c 100644 --- a/components/txs-table/index.tsx +++ b/components/txs-table/index.tsx @@ -2,6 +2,7 @@ import { useTxs } from "@/hooks/api"; import { useDebounce } from "@/hooks/use-debounce"; +import { getFiltersFromParams, setParamsFromFilters } from "@/lib/params"; import { Span, Tx } from "@/types/txs"; import { ColumnDef, @@ -16,6 +17,7 @@ import { getSortedRowModel, useReactTable, } from "@tanstack/react-table"; +import { useSearchParams } from "next/navigation"; import { useEffect, useMemo, useState } from "react"; import { DataTable } from "../data-table"; import { DataTableColumnHeader } from "../data-table/data-table-column-header"; @@ -25,10 +27,13 @@ import { txsColumns } from "./txs-columns"; import { DataTableToolbar } from "./txs-table-toolbar"; export function TxsTable() { + const params = useSearchParams(); const [columnVisibility, setColumnVisibility] = useState({ tags: false, }); - const [columnFilters, setColumnFilters] = useState([]); + const [columnFilters, setColumnFilters] = useState( + getFiltersFromParams(params), + ); const [sorting, setSorting] = useState([]); const operationNameValue = columnFilters.find( @@ -101,6 +106,10 @@ export function TxsTable() { table.setPageSize(15); }, [table]); + useEffect(() => { + setParamsFromFilters(columnFilters); + }, [columnFilters]); + return (
diff --git a/lib/params.ts b/lib/params.ts new file mode 100644 index 0000000..882b609 --- /dev/null +++ b/lib/params.ts @@ -0,0 +1,42 @@ +import { ColumnFiltersState } from "@tanstack/react-table"; +import { ReadonlyURLSearchParams } from "next/navigation"; + +export const getFiltersFromParams = (params: ReadonlyURLSearchParams) => { + let filters: ColumnFiltersState = []; + + const operationName = params.get("operationName"); + operationName && filters.push({ id: "operationName", value: operationName }); + + const tags = params.get("tags"); + if (tags) { + try { + const tagsMap: Map = new Map(JSON.parse(tags)); + filters.push({ id: "tags", value: tagsMap }); + } catch {} + } + + return filters; +}; + +export const setParamsFromFilters = (filters: ColumnFiltersState) => { + const params = new URLSearchParams(); + + const operationName = + (filters.find((filter) => filter.id === "operationName")?.value as + | string + | undefined) ?? undefined; + + const tags = + (filters.find((filter) => filter.id === "tags")?.value as + | Map + | undefined) ?? undefined; + + operationName + ? params.set("operationName", operationName) + : params.delete("operationName"); + tags + ? params.set("tags", JSON.stringify(Array.from(tags))) + : params.delete("tags"); + + window.history.replaceState(null, "", `?${params.toString()}`); +};