T
TanStack2y ago
equal-aqua

Making a rusable table column generic

Hello guys, I am trying to make a reusable table, but having a hard time making the columns props it takes a generic i've tried something like this
type TableProps<
TData extends Record<string, unknown>,
TValue extends Record<string, unknown>
> = {
data: TData[];
columns: ColumnDef<TData, TValue>[];
pageSizeOptions?: string[];
initialPageSize?: number;
isLoading: boolean;
};
type TableProps<
TData extends Record<string, unknown>,
TValue extends Record<string, unknown>
> = {
data: TData[];
columns: ColumnDef<TData, TValue>[];
pageSizeOptions?: string[];
initialPageSize?: number;
isLoading: boolean;
};
` and no luck have also tried other alternatives, but keep getting errors, any ideas, how this should actually look?
3 Replies
equal-aqua
equal-aquaOP2y ago
doing something like this works i guess columns: ColumnDef<TData, any>[]; not sure if this is the correct way to type it
wise-white
wise-white2y ago
I'd probably check out this example from ui shadcn https://ui.shadcn.com/examples/tasks the full code is available here. https://github.com/shadcn-ui/ui/tree/main/apps/www/app/examples/tasks personally I'd have to say I don't like how they mixed the dynamic rendering with the component using useReactTable() here (https://github.com/shadcn-ui/ui/blob/main/apps/www/app/examples/tasks/components/data-table.tsx) and you can go a step further for reusability to have something like this instead
const MyPage = (props?: { pageIndex?: number; pageSize?: number }) => {
const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({
pageIndex: props?.pageIndex ?? 0,
pageSize: props?.pageSize ?? 10,
})

const { data, error, loading } = useQuery(QUERY, {
variables: {
index: pageIndex,
size: pageSize,
},
})

const table = useDataTable({
columns: columns,
page: {
index: pageIndex,
size: pageSize,
data: data?.page?.items,
count: data?.page?.count,
},
onPageChange: setPagination,
})

return (
<>
<DataTable table={table} loading={loading} error={error} />
<DataTablePagination table={table} />
</>
)
}
const MyPage = (props?: { pageIndex?: number; pageSize?: number }) => {
const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({
pageIndex: props?.pageIndex ?? 0,
pageSize: props?.pageSize ?? 10,
})

const { data, error, loading } = useQuery(QUERY, {
variables: {
index: pageIndex,
size: pageSize,
},
})

const table = useDataTable({
columns: columns,
page: {
index: pageIndex,
size: pageSize,
data: data?.page?.items,
count: data?.page?.count,
},
onPageChange: setPagination,
})

return (
<>
<DataTable table={table} loading={loading} error={error} />
<DataTablePagination table={table} />
</>
)
}
equal-aqua
equal-aquaOP2y ago
You can see that the actual table for the prop though, is actually similar to what I’ve tried and didn’t work out

Did you find this page helpful?