Blog>
Snippets

Fetching and Displaying Server-side Data in React Table

Showcases how to fetch data from a server and dynamically display it in a React Table, handling asynchronous operations with useEffect and useState hooks.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useTable } from 'react-table';
Imports the necessary libraries and hooks.
function DataTable() {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const result = await axios('https://api.example.com/data');
      setData(result.data);
    };
    fetchData();
  }, []);

  const columns = React.useMemo(
    () => [
      {
        Header: 'Column 1',
        accessor: 'col1',
      },
      {
        Header: 'Column 2',
        accessor: 'col2',
      },
    ],
    []
  );

  const tableInstance = useTable({ columns, data });

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
  } = tableInstance;
Defines the DataTable component, including state for storing data, fetching data with useEffect when the component mounts, and setting up columns for the table.
return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render('Header')}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map(row => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}
Renders the table using the React Table hooks, iterating over each row and cell to display the data.
export default DataTable;
Exports the DataTable component for use in other parts of the application.