Yashwant Raut
Yashwant Raut

Reputation: 39

How to add lazy loading to react-table with static JSON as data?

Using the react-table v7 library, I'm making a table. The data I'm supplying in this table is prefetched and saved as JSON. This JSON file has the formatting that react-table requires.

But My data is very vast and has numerous deep hierarchies. Expanded option tables are what I'm making. When I feed this data into a react-table, the rendering takes too long, which slows down the application's overall speed.

I want to add lazy loading so that when the user clicks on expand option, the children of that row should get added dynamically from my data. I am referring to this exampleLazy loading in this example the children data is being fetched on click is randomly created there is no hierarchy to maintain. In My case data is already there I want to fetch children of that particular row when the user clicks on expand row button.

In summary, how can I get the children's row when the user clicks on the parent row?

I am attaching a link to code sandbox where I created react table with static data.

Let me know if i am missing anything or you need more details. Thank you

I attempted to implement lazy loading using the aforementioned example, but the data for the lazy loaded row in that example was generated at random, whereas in my situation I wanted to fetch data for the row whose parent row's expand button was pressed.

Upvotes: 0

Views: 2152

Answers (1)

Agan
Agan

Reputation: 497

You can use the useEffect hook to load the data. Try this:

import { useState, useEffect } from 'react';

Create a state variable to store the data, and a state variable to store the current page of data:

const [data, setData] = useState([]);
const [pageData, setPageData] = useState([]);

Use the useEffect:

useEffect(() => {
  // Load the first page of data
  const loadData = async () => {
    // Fetch the data from the JSON file
    const response = await fetch('data.json');
    const jsonData = await response.json();

    // Set the data to the state variable
    setData(jsonData);

    // Set the first page of data to the pageData state variable
    setPageData(jsonData.slice(0, 10));
  };
  loadData();
}, []);

Then pass in the pageData state variable as the data prop

const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({
  data: pageData,
  // ... other table configuration options
});

Add a button to load the next page of data

const handleLoadNextPage = () => {
  // Calculate the next page of data
  const nextPageData = data.slice(pageData.length, pageData.length + 10);

  // Update the pageData state variable with the next page of data
  setPageData([...pageData, ...nextPageData]);
};

And at last, render the table and the button in the component, could look like this:

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, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
    <button onClick={handleLoadNextPage}>Load Next Page</button>
  </>
);

I hope this can help.

Upvotes: 1

Related Questions