Search code examples
reactjsreact-tablereact-usememo

Problems with react-table using "useSortBy"


I am having some problems on react-table using useSortBy. With no useSortBy the table works fine. Getting this error:

Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

var COLUMNS = [
    {
        Header: 'Data Criação',
        accessor: 'createdAt',
        Cell: ({value})=> {return value ? format(new Date(value),  'dd/MM/yyyy') : ''},
    },
    {
        Header: 'Nome',
        accessor: 'name'
    },
    {
        Header: 'Telefone',
        accessor: 'mobile'
    },
    {
        Header: 'Email',
        accessor: 'email'
    },
    {
        Header: 'Action',
        accessor: (hit)=>{
            return <LeadTableAction item={hit} selection={handleLeadDataSelection}/>
        }
    }
]

const columns = useMemo(()=>COLUMNS, []);

const tableInst = useTable({
    columns,
    data:props.lead.leadData ? props.lead.leadData : [{}]
}, useSortBy);

const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
} = tableInst;

On JSX:

<Table {...getTableProps()}>
    <thead>
        {headerGroups.map(hg=>{
           return (
               <tr {...hg.getHeaderGroupProps()}>
                   {hg.headers.map(h=>{
                   return (
                           <th {...h.getHeaderProps(h.getSortByToggleProps())}>
                              {h.render("Header")}
                                <span style={{marginLeft: '5px'}}>
                              {h.isSorted ? (h.isSortedDesc ? <i className="fas fa-sort-down"></i> : <i className="fas fa-sort-up"></i>) : ''}
                              </span>
                           </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>

Can anybody help ?


Solution

  • Problem solved,

    I just add a memo in my code:

    const data = useMemo(()=>{
        return props.lead.leadData ? props.lead.leadData : [{}]
    }, [props.lead.leadData]);
    

    This props.lead is the data to fetch direct on the table. Done! :)