Blog>
Snippets

Server-Side Filtering Logic with React TanStack Table

Provide an example showing how to implement server-side data fetching and filtering based on user input in React TanStack Table, including handling asynchronous requests and updating table data.
import React, { useState, useEffect } from 'react';
import { useTable } from '@tanstack/react-table';
Import necessary hooks from React and the useTable hook from @tanstack/react-table.
const fetchData = async (filter) => {
  const response = await fetch(`YourAPIEndpoint?filter=${filter}`);
  const data = await response.json();
  return data;
};
Defines an asynchronous function to fetch data from an API endpoint, applying the filter parameter from the user input.
const Table = ({ columns }) => {
  const [data, setData] = useState([]);
  const [filter, setFilter] = useState('');

  useEffect(() => {
    const loadFilteredData = async () => {
      const filteredData = await fetchData(filter);
      setData(filteredData);
    };
    loadFilteredData();
  }, [filter]);
Sets up a React component for the table. It uses useState to manage the data and the current filter. useEffect triggers loading the data when the filter changes.
const instance = useTable({
    data,
    columns,
  });
Initializes the table instance using the useTable hook, passing in the data and columns.
return (
    <div>
      <input
        value={filter}
        onChange={e => setFilter(e.target.value)}
        placeholder="Search..."
      />
      <div>{instance.getTableProps()}</div>
    </div>
  );
};
Renders an input field for the filter and the table. The input's onChange event updates the filter state, triggering data fetching with the new filter.
export default Table;
Exports the Table component for use in other parts of the application.