Fetching data using the Tanstack table in Next.js – Next.js

by
Ali Hasan
next.js reactjs tanstackreact-query

Quick Fix: In the DataTable component, utilize the useEffect hook with an internal state to update data based on user input. Fetch data from the specified URL and assign it to the internal data state upon successful fetching. This approach maintains SEO while accommodating dynamic data updates driven by user actions.

The Problem:

How to fetch data effectively for a Tanstack table in Next.js while maintaining the best practices?

The Solutions:

Solution 1: Using an internal state and useEffect

  1. In the DataTable functional component, add an internal state variable internalData to hold the data that will be displayed in the table.
  2. Use the useEffect hook to fetch data from the server and update the internalData state variable. The useEffect hook will be called when the component is mounted and when the pageSize state variable changes.
  3. In the useEffect hook, make an API call to the server to fetch the data. Use the pageSize state variable to specify the number of rows to return from the server.
  4. Parse the response from the server to extract the data.
  5. Update the internalData state variable with the fetched data.

The following code shows how to implement this solution:

import { use client } from "react-query";

// ...

const DataTable = <TData, TValue>(
  { columns, data }: DataTableProps<TData, TValue>
) => {
  const [internalData, setInternalData] = React.useState(data);
  const initialRenderRef = React.useRef(true);
  const clientQuery = useClient();
  const table = useReactTable({
    columns,
    data: internalData,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    getFilteredRowModel: getFilteredRowModel(),
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    state: {
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
    },
  });

  React.useEffect(() => {
    if (initialRenderRef.current) {
      initialRenderRef.current = false;
      return;
    }

    const fetchData = async () => {
      try {
        // Make an API call to the server to fetch the data
        const response = await clientQuery.get('url');
        const data = await response.json();
        setInternalData(data);
      } catch (error) {
        console.log(error);
      }
    };

    fetchData();
  }, [pageSize]);

  return " ... ";
};

export default DataTable;

When the pageSize state variable changes, the useEffect hook will be called, and the data will be fetched from the server again. This will ensure that the data displayed in the table is always up to date.

Q&A

What is the best practice to fetch data for Tanstack table?

Use useEffect with an internal state to update the data in the DataTable according to user input.

How to update data in DataTable according to user input?

Use useEffect with an internal state to fetch data and update the DataTable.

Video Explanation:

The following video, titled "Tables in NextJs Using shadcn/ui and TanStack Table - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

This video will look at creating data tables in NextJs using the shadcn/ui and the TanStack table libraries. We'll implement pagination, ...