I want to use a React library so i tried looking for a library and saw this tanstack v8 table. I followed a tutorial on basic table but im getting some errors.
//Parent next component
'use client'
import React, { useEffect, useState } from 'react'
import BasicTable from '../components/BasicTable'
import axios from 'axios';
export default function Vendor() {
const [defaultData, setDefaultData] = useState(null)
useEffect(() => {
const generateData = async() => {
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => setDefaultData(response.data))
}
generateData()
}, [])
const columns = [
{
id: 1,
label: 'user ID',
accessorKey: 'userID'
},
{
id: 2,
label: 'id',
assecorKey: 'id'
},
{
id: 3,
label: 'body',
accesorKey: 'body'
},
{
id: 4,
label: 'title',
assecorKey: 'title'
},
]
return (
<div>
<h1>Vendor</h1>
<BasicTable data={defaultData} columns={columns}/>
</div>
)
}
The data that i'm getting from the api is these:
(100) [{0
:
body
:
"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
id
:
1
title
:
"sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
userId
:
1}]
BasicTable component
import React from "react";
import {
useReactTable,
getCoreRowModel,
flexRender,
} from "@tanstack/react-table";
import { useMemo } from "react";
export default function BasicTable({ data, columns }) {
const dataTable = useMemo(() => data);
const table = useReactTable({
dataTable,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div>
Basic table
<div className="border-solid border-2 rounded mt-5">
<table>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th key={header.id}>
{flexRender(
header.column.columnDef.label,
header.getContext()
)}
</th>
))}
</tr>
))}
<tbody>
{table.getRowModel().rows.map(row => (
<tr key={row.id}>
{row.getVisibleCells().map(cell => (
<td key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
<tr>
<td>id</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
I'm getting errors when i'm mapping the data rows. I'm new to using this library. I've already check and it seems that I'm getting the erros from the table.getRowModel()
Have you tried awaiting the API response? If that doesn't work, try initializing the table with mock data, to see if that works.