/
next-datatable-example.tsx
132 lines (121 loc) · 2.87 KB
/
next-datatable-example.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
'use client';
import { useEffect, useState } from 'react';
import {
NextDataTable,
useGetNextTableState,
} from '@lifespikes/next-datatable';
import { ColumnDef } from '@tanstack/react-table';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
CheckboxPrimitive,
} from '@lifespikes/ui';
export const columns: ColumnDef<Product>[] = [
{
id: 'select',
header: ({ table }) => (
<CheckboxPrimitive
checked={table.getIsAllPageRowsSelected()}
onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
aria-label="Select all"
/>
),
cell: ({ row }) => (
<CheckboxPrimitive
className="border-gray-400 data-[state=checked]:border-white"
checked={row.getIsSelected()}
onCheckedChange={(value) => row.toggleSelected(!!value)}
aria-label="Select row"
/>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: 'id',
header: 'Id',
},
{
accessorKey: 'title',
header: 'Title',
},
{
accessorKey: 'description',
header: 'Description',
},
];
export interface DummyApiResponse {
products: Product[];
total: number;
skip: number;
limit: number;
}
export interface Product {
id: number;
title: string;
description: string;
price: number;
discountPercentage: number;
rating: number;
stock: number;
brand: string;
thumbnail: string;
images: string[];
}
/** @see https://dummyjson.com/docs/products */
const request = async (
page: number,
perPage = 10
): Promise<DummyApiResponse> => {
const response = await fetch(
`https://dummyjson.com/products?limit=${perPage}&skip=${
(page - 1) * perPage
}`
);
return response.json();
};
const NextDatatableExample = () => {
const [data, setData] = useState<DummyApiResponse | null>(null);
const [isLoading, setIsLoading] = useState(false);
const { pagination } = useGetNextTableState();
useEffect(() => {
(async () => {
setIsLoading(true);
const data = await request(
(pagination?.pageIndex ?? 0) + 1,
pagination.pageSize ?? 10
);
setData(data);
setIsLoading(false);
})();
}, [pagination]);
const totalPages = Math.ceil(
(data?.total ?? 0) / (pagination?.pageSize ?? 10)
);
return (
<Card>
<CardHeader>
<CardTitle>Next Datatable</CardTitle>
<CardDescription>Minimal example of usage</CardDescription>
</CardHeader>
<CardContent>
<NextDataTable
defaultValues={{
pagination: {
pageSize: data?.limit ?? 10,
pageIndex: (data?.skip ?? 1) - 1,
},
}}
pageCount={totalPages}
data={data?.products ?? []}
columns={columns}
isLoading={isLoading}
/>
</CardContent>
</Card>
);
};
export default NextDatatableExample;