I am using react-table using tanstack library and facing problem where Table renders before data is available. I have tried setting it to default empty [] or using useMemo pointed in earlier posts but no luck.
Is there some problem in how I am using useEffect? Note this is using client-side rendering.Simplified version of the parent component and DataTable component are below Also added the error below
The error is
Cannot read properties of undefined (reading 'length'). and it points out to line {table.getRowModel().rows.map
'use client'
import React, { useEffect, useState } from 'react'
import DataTable from '../components/DataTable'
import axios from 'axios';
export default function MainPage() {
const [data, setData] = useState([])
useEffect(() => {
const data = getReports();
setData(data);
}, [])
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>Reports</h1>
<DataTable data={data} columns={columns}/>
</div>
)
import React from "react";
import {
useReactTable,
getCoreRowModel,
flexRender,
} from "@tanstack/react-table";
export default function DataTable({ data, columns }) {
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
});
return (
<div>
<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>
);
}