"use client"; import React from "react"; import { useReactTable, flexRender, getCoreRowModel, createColumnHelper, } from "@tanstack/react-table"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableFooter, } from "@/components/ui/table"; import { getIconByName } from "@/Icons/icons"; import { useRouter } from "next/navigation"; import { encryptQuery, handleUpdateSubmission } from "@/apicalls/test"; import SingleTableHeader from "./SingleTableHeader"; interface TableComponentInterFace { restrictions: any; query: any; orderByValue: string; orderTypeValue: string; } const TableComponent: React.FC = ({ restrictions, query, orderByValue, orderTypeValue, }) => { const router = useRouter(); const [updateRow, setUpdateRow] = React.useState(null); const [columns, setColumns] = React.useState([]); const [orderBy, setOrderBy] = React.useState<"asc" | "desc">( orderByValue as "asc" | "desc" ); const [orderColumn, setOrderColumn] = React.useState(orderTypeValue); const columnHelper = createColumnHelper(); const table = useReactTable({ data: restrictions.table?.data?.data || [], columns, getCoreRowModel: getCoreRowModel(), }); React.useEffect(() => { if (restrictions?.table?.headers) { setColumns(createColumnsFromValidations(restrictions.table.headers)); } }, [restrictions.table.headers]); React.useEffect(() => { if (updateRow) { encryptQuery(updateRow).then((encryptData) => { router.push(`/building/update?q=${encryptData.replaceAll(" ", "+")}`); }); } }, [updateRow]); function createColumnsFromValidations(headers: any) { const columns = Object.entries(headers).map(([key]: [string, any]) => { return columnHelper.accessor(key, { id: key, footer: headers[key], header: () => {headers[key]}, cell: (info) => {info.getValue()}, }); }); if (restrictions?.update) { columns.push( columnHelper.accessor("update", { id: "update", footer: "Update", header: () => Update, cell: () => (
{restrictions?.update.icon && React.createElement(getIconByName(restrictions?.update.icon))}
), }) ); } return columns; } function changeOrderState(headerID: string) { console.log("changeOrderState", headerID, orderColumn, orderBy); if (orderColumn === headerID) { setOrderBy(orderBy === "asc" ? "desc" : "asc"); } else { setOrderColumn(headerID); setOrderBy("asc"); } } return ( <>

{JSON.stringify(updateRow)}

{table.getHeaderGroups().map((headerGroup) => ( {headerGroup.headers.map((header) => ( ))} ))} {table.getRowModel().rows?.length ? ( table.getRowModel().rows.map((row) => ( {row.getVisibleCells().map((cell) => cell.column.id !== "update" ? ( {flexRender( cell.column.columnDef.cell, cell.getContext() )} ) : ( setUpdateRow(row.original)} > {flexRender( cell.column.columnDef.cell, cell.getContext() )} ) )} )) ) : ( No results. )} {table.getFooterGroups().map((footerGroup) => ( {footerGroup.headers.map( (footer) => footer.id !== "update" && ( {footer.isPlaceholder ? null : ( )} ) )} ))}
); }; export default TableComponent;