0

The data is coming from api.php file as json through useEffect. How do I display this data in the table?

Here is my current code:

import React,{ useEffect, useState, useMemo } from 'react';
import {
    flexRender,
    getCoreRowModel,
    getFilteredRowModel,
    getPaginationRowModel,
    getSortedRowModel,
    useReactTable,
  } from '@tanstack/react-table'

export default function Ticket(){

const [tickets, setTickets] = useState([])
const [loading, setLoading] = useState(true);

    useEffect(()=>{
        fetch("http://localhost:8000/api/tickets")
        .then(res => res.json())
        .then(data => {
          setTickets(data);
          setLoading(false); 
        })
        .catch(error => {
          console.error("Error fetching data:", error);
          setLoading(false); 
        });
    },[])



    const columns = [
        {
            header: 'ID',
            accessorKey: 'ticket_id'
        },
        {
            header: 'Case Content',
            accessorKey: 'caseContent'
        },
        {
            header: 'Case Subject',
            accessorKey: 'caseSubject'
        },
        {
            header: 'Case Date',
            accessorKey: 'caseDate'
        },
        {
            header: 'Case Title',
            accessorKey: 'caseTitle'
        },
    ]

const table = useReactTable({ 
                            data:tickets,
                            columns,
                            getCoreRowModel: getCoreRowModel()
                        })
const isTableReady = table && table.getRowModel() && table.getRowModel().rows;

return (
    <div>
      {loading ? (
        <p>Loading...</p> // Display a loading indicator while data is being fetched
      ) : (
        <table>
          <thead>
            {table.getHeaderGroups().map(headerGroup => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map(header => (
                  <th key={header.id}>
                    {flexRender(
                      header.column.columnDef.header,
                      header.getContext()
                    )}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          {isTableReady && (
           <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>
           ))}
         </tbody>
          )}
        </table>
      )}
    </div>
  );
}

I used the useEffect to bring in my data and use conditional rendering to wait for the state to be updated with data but i did not work. Only the headers are displaying and not the data itself.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56

0 Answers0