最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - react tanstack datatable error in rendering - Stack Overflow

programmeradmin0浏览0评论

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>
  );
}
发布评论

评论列表(0)

  1. 暂无评论