'Conditionally load a hook

I'm setting up a table component, and I want it to have a table loading shimmer component render if the data is still loading.

Now I'm passing the data to the table component, and loading it in a custom hook from React Table package. The thing is, when the data goes there and the data hasn't been loaded I get an error. That's because the data is being looped over to render it.

So I want the data to either not be looped over yet, or have some kind of default argument.

I've tried to add a default array with an empty object in it, but then I get the same error.

I could have the component which calls the table render it conditionally, but I think it would be nice to make the table be able to do it.

My table component:

const Table = ({ headerTxt, columns, data, isLoading }) => {
  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } =
    useTable({
      columns,
      data,
    });

  return (
    <Wrapper>
      <Header>
        <h6>{headerTxt}</h6>
      </Header>
      {isLoading ? (
        <>Loading component goes here</>
      ) : (
        <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>
      )}
    </Wrapper>
  );
};

export default Table;

Does someone know how I can do this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source