Build a Finance SaaS Platform -11 (Delete API)

Modify Columns

Modify app/(dashboard)/accounts/columns.tsx:

(delete demo columns)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"use client"
import { InferResponseType } from "hono";
import { ColumnDef } from "@tanstack/react-table";
import { ArrowUpDown } from "lucide-react";

import { client } from "@/lib/hono";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";

export type ResponsType = InferResponseType<typeof client.api.accounts.$get, 200>["data"][0];

export const columns: ColumnDef<ResponsType>[] = [
{
id: "select",
header: ({ table }) => (
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() && "indeterminate")
}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "name",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
Name
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
)
},
},
]

Change Page

Modify app/(dashboard)/accounts/page.tsx:

Add loading logic,Add Bulk Delete Action

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"use client";

import { Loader2, Plus } from "lucide-react";
import { useNewAccount } from "@/features/accounts/hooks/use-new-account";
import { useGetAccounts } from "@/features/accounts/api/use-get-accounts";
import { useBulkDeleteAccounts } from "@/features/accounts/api/use-bulk-delete";

import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";

import { columns } from "./columns";
import { DataTable } from "@/components/data-table";

const AccountsPage = ()=> {
const newAccount = useNewAccount();
const deleteAccount = useBulkDeleteAccounts();
const accountQuery = useGetAccounts();
const accounts = accountQuery.data || [];

const isDisabled = accountQuery.isLoading || deleteAccount.isPending;

//Add Loading Logic
if( accountQuery.isLoading) {
return (
<div className="max-w-screen-2xl max-auto w-full pb-10 -mt-24">
<Card className="border-none drop-shadow-sm">
<CardHeader>
<Skeleton className="h-8 w-48" />
</CardHeader>
<CardContent>
<div className="h-[500px] w-full flex items-center">
<Loader2 className="size-6 text-slate-300 animate-spin" />
</div>
</CardContent>
</Card>
</div>
)
};

return (
<div className="max-w-screen-2xl mx-auto w-full pb-10 -mt-24">
<Card className="border-none drop-shadow-sm">
<CardHeader className="gap-y-2 lg:flex-row lg:items-center lg:justify-between">
<CardTitle className="text-xl line-clamp-1">
Account Page
</CardTitle>
<Button onClick={newAccount.onOpen} size="sm">
<Plus className="size-4 mr-2" />
Add New
</Button>
</CardHeader>
<CardContent>
<DataTable
filterKey = "name"
columns={columns}
data={ accounts }
onDelete={(rows)=>{
const ids = rows.map((r) => r.id)
deleteAccount.mutate({ ids });
}}
disabled={isDisabled}
/>
</CardContent>
</Card>
</div>
);
};

export default AccountsPage;

Add API Logic

Modify app/api/[[...route]]/accounts.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { z } from "zod"
import { and, eq, inArray } from "drizzle-orm";
...
.post(
"/bulk-delete",
clerkMiddleware(),
zValidator(
"json",
z.object({
ids: z.array(z.string())
}),
),
async (c) =>{
const auth = getAuth(c);
const values = c.req.valid("json");

if (!auth?.userId) {
return c.json({ error: "Unauthorized"}, 401 );
}

const data = await db
.delete(accounts)
.where(
and(
eq(accounts.userId, auth.userId),
inArray(accounts.id, values.ids)
)
)
.returning({
id: accounts.id,
});

return c.json({ data });
},
)
...

Add Confirm Dialog:

Add hooks/use-confirm.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { useState } from "react";

import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";

export const useConfirm = (
title: string,
message: string,
): [()=> JSX.Element,()=> Promise<unknown>] => {
const [promise, setPromise] = useState<{ resolve:(value: boolean)=> void} | null>(null)

const confirm = () => new Promise((resolve, reject) =>{
setPromise({ resolve });
})

const handleClose = () => {
setPromise(null);
}

const handleConfirm = ()=> {
promise?.resolve(true);
handleClose();
}

const handleCancel = () => {
promise?.resolve(false);
handleClose();
}

const ComfirmationDialog = () => (
<Dialog open={promise != null}>
<DialogContent>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{message}</DialogDescription>
</DialogHeader>
<DialogFooter className="pt-2">
<Button
onClick={handleCancel}
variant="outline"
>
Cancel
</Button>
<Button onClick={handleConfirm}>
Confirm
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);

return [ComfirmationDialog, confirm];
}

Modify Data Table:

Modify components/data-table.tsx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
"use client"

import React from "react";
import {
ColumnDef,
ColumnFiltersState,
SortingState,
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
getFilteredRowModel,
useReactTable,
} from "@tanstack/react-table";

import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { useConfirm } from "@/hooks/use-confirm";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Trash } from "lucide-react";

interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]
data: TData[]
filterKey: string
onDelete: (row: TData[]) => void
disabled?: boolean
}

export function DataTable<TData, TValue>({
columns,
data,
filterKey,
onDelete,
disabled,
}: DataTableProps<TData, TValue>) {
const [ConfirmDialog, confirm] = useConfirm(
"Are you sure?",
"You are about to perform a bulk delete."
);

const [sorting, setSorting] = React.useState<SortingState>([]);
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>([]);
const [rowSelection, setRowSelection] = React.useState({})

const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
onSortingChange: setSorting,
onColumnFiltersChange: setColumnFilters,
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
onRowSelectionChange: setRowSelection,
state: {
sorting,
columnFilters,
rowSelection,
},
})

return (
<div>
<ConfirmDialog />
<div className="flex items-center py-4">
<Input
placeholder={`Filter ${filterKey} ...`}
value={(table.getColumn(filterKey)?.getFilterValue() as string) ?? ""}
onChange={(event) =>
table.getColumn(filterKey)?.setFilterValue(event.target.value)
}
className="max-w-sm"
/>
{ table.getFilteredSelectedRowModel().rows.length > 0 && (
<Button
disabled={disabled}
size="sm"
variant="outline"
className="ml-auto font-normal text-xs"
onClick={async ()=>{
const ok = await confirm();

if (ok){
onDelete(table.getFilteredSelectedRowModel().rows.map(row => row.original));
table.resetRowSelection();
}
}}
>
<Trash className="size-4 mr-2" />
Delete({table.getFilteredSelectedRowModel().rows.length})
</Button>
)}
</div>
<div className="rounded-md border">
<Table>
<TableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</TableHead>
)
})}
</TableRow>
))}
</TableHeader>
<TableBody>
{table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-24 text-center">
No results.
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<div className="flex items-center justify-end space-x-2 py-4">
<div className="flex-1 text-sm text-muted-foreground">
{table.getFilteredSelectedRowModel().rows.length} of{" "}
{table.getFilteredRowModel().rows.length} row(s) selected.
</div>
<Button
variant="outline"
size="sm"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
Previous
</Button>
<Button
variant="outline"
size="sm"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
Next
</Button>
</div>
</div>
)
}

Install Dialog&Skeleton

1
2
npx shadcn@latest add dialog
npx shadcn@latest add skeleton

请我喝杯咖啡吧~

支付宝
微信