Reputation: 31
I created a data table using ChadCN’s guide, which uses @tanstack/react-table. Each row has a dropdown menu with three dots, allowing the user to remove the row. The dropdown triggers a removeDomain server function that deletes the database entry by ID, and it works fine.
However, the table does not refresh after the row is removed. I want to update the table without a page reload. I tried using callback functions, but I’m struggling to integrate them due to the dynamic column and row construction in TanStack.
This is the component with the delete action:
export function DataTableRowActions<TData>({
row,
}: DataTableRowActionsProps<TData>) {
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
className="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
>
<MoreHorizontal />
<span className="sr-only">Open menu</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-[160px]">
<DropdownMenuItem
onClick={() => {
const id = (row.original as { id: number }).id;
removeDomain(id); //imported server function
}}
>
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
The dropdown component for the “Remove” action is called from the component that builds the columns:
export const getDomainColumns: ColumnDef<initialDomain>[] = [
{
accessorKey: "domain",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Domain" />
),
cell: ({ row }) => {
return (
<div className="flex space-x-2">
{/* {label && <Badge variant="outline">{label.label}</Badge>} */}
<span className="max-w-[500px] truncate font-medium">
{row.getValue("domain")}
</span>
</div>
);
},
},
{
accessorKey: "createdAt",
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Date Added" />
),
cell: ({ row }) => {
return (
<div className="flex space-x-2">
{/* {label && <Badge variant="outline">{label.label}</Badge>} */}
<span className="max-w-[500px] truncate font-medium">
{row.getValue("createdAt")}
</span>
</div>
);
},
},
{
id: "actions",
cell: ({ row }) => <DataTableRowActions row={row} />,
},
];
This is where the table component is called, and the columns and data is given. The columns are given using the component above.
return (
<div className="flex flex-1 flex-col gap-4 p-4 pt-0">
<div className="min-h-[100vh] flex-1 md:min-h-min">
<InitialDomainsDataTable
columns={getDomainColumns}
data={initialDomains}
/>
</div>
</div>
);
}
The column data is used to build the TanStack table in the InitialDomainsDataTable component.
const table = useReactTable({
data: domains,
columns,
state: {
sorting,
},
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
});
What would be the best way to solve this?
Upvotes: 0
Views: 36