table icon indicating copy to clipboard operation
table copied to clipboard

Getting Maximun call stack In production.

Open pavittars opened this issue 6 years ago • 20 comments

I'm getting maximum call stack in production but during dev, it's working fine. Follow is the code I'm using.

import React, { useEffect } from 'react';
import { useTable, usePagination, useSortBy, useRowSelect } from 'react-table';
import Arrow from '../../assets/img/arrow.png';
import SortArrow from '../../assets/img/downarrow.png';
export default function Table({ columns = [], data = [], _setSelected }) {

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    // rows,
    prepareRow,
    pageOptions,
    page,
    state: { pageIndex, selectedRowPaths },
    previousPage,
    nextPage,
    canPreviousPage,
    canNextPage,
    selectedFlatRows
  } = useTable(
    {
      columns,
      data,
      disableSortRemove: true,
    },
    useSortBy,
    useRowSelect,
    usePagination
  );

  useEffect(
    () => {
      _setSelected(selectedFlatRows);
    },
    [selectedRowPaths, selectedFlatRows]
  );

  return (
    <>
      <div className="table-responsive">
        <table
          {...getTableProps()}
          className="w-100 table table-bordered table-striped table-hover"
        >
          <thead>
            {headerGroups.map((headerGroup) => (
              <tr {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map((column) => (
                  <th scope="col" {...column.getHeaderProps(column.getSortByToggleProps())}>
                    {column.render('Header')}
                    {column.isSorted && <img src={SortArrow} width="18" className={column.isSortedDesc?'':'rotate-up'} alt="sorting" />}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody {...getTableBodyProps()}>
            {page.map((row, i) => {
              prepareRow(row);

              return (
                <tr {...row.getRowProps()}>
                  {row.cells.map((cell) => {
                    return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
                  })}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
            {data.length > 10 && <>
      <div className="text-center">
        Page{' '}
        <em>
          {pageIndex + 1} of {pageOptions.length}
        </em>
      </div>
      <div className="text-center">
        <button
          className="btn btn-primary"
          onClick={() => previousPage()}
          disabled={!canPreviousPage}
        >
          <img src={Arrow} className="previous-arrow" alt="Previous" />
        </button>
        <button
          className="btn btn-primary"
          onClick={() => nextPage()}
          disabled={!canNextPage}
        >
          <img src={Arrow} className="next-arrow" alt="Next" />
        </button>
      </div>
      </>}
    </>
  );
}

pavittars avatar Dec 09 '19 10:12 pavittars

Are you using the latest release candidate version?

tannerlinsley avatar Dec 09 '19 15:12 tannerlinsley

@tannerlinsley i'm using "react-table": "^7.0.0-rc.6" this version.

pavittars avatar Dec 10 '19 05:12 pavittars

Comment out the effect. Does it still happen?

tannerlinsley avatar Dec 10 '19 05:12 tannerlinsley

After commenting the effect works it's fine.

pavittars avatar Dec 10 '19 05:12 pavittars

That is strange. useEffect should not be running in an SSR environment. What are you building your app in? Next?

tannerlinsley avatar Dec 10 '19 05:12 tannerlinsley

I'm using Reactjs

pavittars avatar Dec 10 '19 05:12 pavittars

Yes, but how and when are you doing server side rendering?

tannerlinsley avatar Dec 10 '19 05:12 tannerlinsley

No, we are not doing the SSR. Running the app using the express server.

pavittars avatar Dec 10 '19 05:12 pavittars

So you are rendering the app html Using express, then using React normally on the client?

tannerlinsley avatar Dec 10 '19 05:12 tannerlinsley

I’ve updated the issue to better reflect the question you’re asking.

tannerlinsley avatar Dec 10 '19 05:12 tannerlinsley

What’s happening is that your effect is using a dependency that is likely changing from the effect itself. Thus you get an infinite call stack.

tannerlinsley avatar Dec 10 '19 06:12 tannerlinsley

I think the best thing to do here is to make a codesandbox that illustrates the issue. It will be 100x easier for me to debug from there.

tannerlinsley avatar Dec 10 '19 14:12 tannerlinsley

Please comment with a codesandbox demonstrating the issue and we can reopen this issue :)

tannerlinsley avatar Dec 10 '19 18:12 tannerlinsley

I'm facing a similar issue, I also have a similar code than him.

Something i could add is the _setSelected (named setSelectedRows) function passed in params to his Table component, is setting the state in the parent component. So it causes a rerendering of the Table component which changes selectedFlatRows (maybe ?) so the useEffect is called again so the infinite loop starts again and again.

To solve this issue, i remove the this.setState({selectedRows}) i had in the setSelectedRows (_setSelected equivalent in your code) and replaced it by this.selectedRows = selectedRows. So selectedRows isn't no more part of the state, so it won't call render method of parent component and the table component won't be rerender and causes that infinite loop.

It worked for me because i didn't really need that selectedRows in the parent component state, but what if i really needed it ? How can i solve this ? 'Cause i think i'm gonna soon need it.

EDIT : i'm using "react-table": "^7.0.0-rc.15"

shiglet avatar Jan 06 '20 08:01 shiglet

... It worked for me because i didn't really need that selectedRows in the parent component state, but what if i really needed it ? How can i solve this ? 'Cause i think i'm gonna soon need it.

EDIT : i'm using "react-table": "^7.0.0-rc.15"

I've found workaround for this issue, insipred by this conversation

First you have to set initialState.selectedRowIds but make sure it's never recreated during render:

const INITIAL_SELECTED_ROW_IDS = {};

const DataTable = ({ data, columns, onSelectedRowChange }) => {
    const {
        getTableProps,
        page,
        prepareRow,
        headerGroups,
        pageCount,
        gotoPage,
        state: { pageIndex, selectedRowIds },  // selectedRowPaths is renamed to selectedRowIds
    } = useTable(
        {
            data,
            columns,
            initialState: {
                pageSize: pageSize,
                selectedRowIds: INITIAL_SELECTED_ROW_IDS  // Do not just use {}
            }
        },

...

and re-implement selectedFlatRows's behavior like this:

import { useMountedLayoutEffect } from "react-table";
...

    useMountedLayoutEffect(() => {
        const selectedIds = Object.keys(selectedRowIds);
        var selectedRowsData = selectedIds
            .map(x => data[x])
            .filter(function(x) {
                return x != null;
            });

        onSelectedRowChange(selectedRowsData);
    }, [onSelectedRowChange, selectedRowIds]);

iAmGhost avatar Feb 06 '20 08:02 iAmGhost

@iAmGhost : is it mandatory to give initialState for selectedRowIds , beacuse UI will load with pre-selected rows , is there any other way ?

vishwa3 avatar Jul 14 '20 07:07 vishwa3

I am running into this issue as well. It runs regardless of whether or not a selection was made.

austincondiff avatar Feb 15 '22 20:02 austincondiff

I hit this same thread and eliminated the infinite rendering by adding autoResetHiddenColumns: false to the useTable call:

const tableInstance = useTable({
  columns,
  data,
  autoResetHiddenColumns: false,    //  <-- stops the rerendering 🥳
}, useSortBy);

duhaime avatar Mar 31 '22 20:03 duhaime

It is very strange behavior and it is hint when using react-table select rows feature. That's work for me:

const tableInstance = useTable({
  columns,
  data,
  autoResetHiddenColumns: false,    //  <-- stops the rerendering 🥳
  autoResetSortBy: false, //  <-- stops the rerendering 🥳
}, useSortBy);

paveltretyakovru avatar May 27 '22 03:05 paveltretyakovru

None of the above (or anywhere else on the interwebs) worked for me but here's what did. And I imagine, with the number of people who've asked this same question about React Table v7, that in version 8 of React Table, the state, especially state having to do with selection, has been ironed out. But anyway this is the ONLY workaround that worked for me, loosely based on this codesandbox.

// Parent component

  1. I used a useCallback hook to prevent my setSelectedRows (your setSelection) function being passed to the child as a new function and kicking off multiple renders.

  2. And I passed in an initial state that sets React Table's selectedRowIds with the parent's selectedRows:

const ParentDoingParentyThings = () => {
  const [selectedRows, setSelectedRows] = React.useState({});
  const handleSelection = React.useCallback((value) => {
    setSelectedRows(value);   
    }, []); 

return (
  <Table
        data={tableData}
        setSelectedRows={handleSelection}
        initialState={{ sortBy: [{ id: 'totalSeries', desc: true }], selectedRowIds: selectedRows }}
        ...
      />
  )
}

// And the Table / child Then!...

  1. I use this lesser know function from React Table called useMountedLayoutEffect. Dont ask me in detail what it does, but it works, that's what it does....
  2. Then I pull from RT's selectedRowIds state
  3. And I use RT's useMountedLayoutEffect function like I would a useEffect
import {
  ...
  useMountedLayoutEffect,
} from 'react-table';

export const Table = ({
  data,
  setSelectedRows,
  initialState,
  ...
}: Props) => {
  ...
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow,
    state: { selectedRowIds },
  } = useTable(
    {
      data: tableData,
      initialState,
      ...
    },
    useSortBy,
    useRowSelect,
  );

  useMountedLayoutEffect(() => {
    setSelectedRows && setSelectedRows(selectedRowIds);
  }, [setSelectedRows, selectedRowIds]);

  return (
    <table {...getTableProps()} className={className}>
      ...
    </table>

CatPerry avatar Jul 09 '22 15:07 CatPerry