react-table#useAsyncDebounce TypeScript Examples

The following examples show how to use react-table#useAsyncDebounce. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From platform with MIT License 6 votes vote down vote up
// Define a default UI for filtering
function GlobalFilter({
  preGlobalFilteredRows,
  globalFilter,
  setGlobalFilter,
  searchPlaceholder,
}) {
  const count = preGlobalFilteredRows.length;
  const [value, setValue] = React.useState(globalFilter);
  const onChange = useAsyncDebounce((value) => {
    setGlobalFilter(value || undefined);
  }, 200);

  return (
    <div className="relative bg-white border border-gray-300 rounded-md px-3 py-2 shadow-sm focus-within:ring-1 focus-within:ring-teal-600 focus-within:border-teal-600">
      <label
        htmlFor="name"
        className="absolute -top-2 left-2 -mt-px inline-block px-1 bg-white text-xs font-medium text-gray-900"
      >
        Search
      </label>
      <input
        type="text"
        className="block w-full border-0 p-0 text-gray-900 placeholder-gray-500 focus:ring-0 text-sm"
        value={value || ""}
        onChange={(e) => {
          setValue(e.target.value);
          onChange(e.target.value);
        }}
        placeholder={`${count} ${searchPlaceholder}`}
      />
    </div>
  );
}
Example #2
Source File: index.tsx    From interbtc-ui with Apache License 2.0 6 votes vote down vote up
// TODO: not used for now
function GlobalFilter({ preGlobalFilteredRows, globalFilter, setGlobalFilter }) {
  const count = preGlobalFilteredRows.length;
  const [value, setValue] = React.useState(globalFilter);
  const onChange = useAsyncDebounce((value) => {
    setGlobalFilter(value || undefined);
  }, 200);

  return (
    <span>
      Search:&nbsp;
      <input
        className={clsx('text-lg', 'border-0')}
        value={value || ''}
        onChange={(event) => {
          setValue(event.target.value);
          onChange(event.target.value);
        }}
        placeholder={`${count} records...`}
      />
    </span>
  );
}
Example #3
Source File: index.tsx    From polkabtc-ui with Apache License 2.0 6 votes vote down vote up
function GlobalFilter({
  preGlobalFilteredRows,
  globalFilter,
  setGlobalFilter
}) {
  const count = preGlobalFilteredRows.length;
  const [value, setValue] = React.useState(globalFilter);
  const onChange = useAsyncDebounce(value => {
    setGlobalFilter(value || undefined);
  }, 200);

  return (
    <span>
      Search:&nbsp;
      <input
        className={clsx(
          'text-lg',
          'border-0'
        )}
        value={value || ''}
        onChange={event => {
          setValue(event.target.value);
          onChange(event.target.value);
        }}
        placeholder={`${count} records...`} />
    </span>
  );
}
Example #4
Source File: ViewAllTable.tsx    From devex with GNU General Public License v3.0 4 votes vote down vote up
ViewAllTable: React.FC<IViewAllTableParams<DsBlockObj | TxBlockObj | TransactionDetails>> =
  ({ columns, data, isLoading, fetchData, pageCount: controlledPageCount }) => {

    const { getTableProps,
      getTableBodyProps,
      headerGroups,
      prepareRow,
      page,
      canPreviousPage,
      canNextPage,
      pageCount,
      gotoPage,
      nextPage,
      previousPage,
      // Get the state from the instance
      state: { pageIndex } } = useTable<DsBlockObj | TxBlockObj | TransactionDetails>({
        columns,
        data,
        initialState: { pageIndex: 0 },
        manualPagination: true,
        pageCount: controlledPageCount,
      }, usePagination)

    const fetchDataDebounce = useAsyncDebounce(fetchData, 300)

    useEffect(() => {
      fetchDataDebounce({ pageIndex })
      // fetchDataDebounce changes when fetchData function changes
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pageIndex, fetchData])

    const generatePagination = useCallback((currentPage: number, pageCount: number, delta = 2) => {
      const separate = (a: number, b: number, isLower: boolean) => {
        const temp = b - a
        if (temp === 0)
          return [a]
        else if (temp === 1)
          return [a, b]
        else if (temp === 2)
          return [a, a + 1, b]
        else
          return [a, isLower ? -1 : -2, b]
      }

      return Array(delta * 2 + 1)
        .fill(0)
        .map((_, index) => currentPage - delta + index)
        .filter(page => 0 < page && page <= pageCount)
        .flatMap((page, index, { length }) => {
          if (!index) {
            return separate(1, page, true)
          }
          if (index === length - 1) {
            return separate(page, pageCount, false)
          }
          return [page]
        })
    }, [])

    return (
      <>
        <BRow>
          <BCol className='align-self-center pl-3'>
            {data.length === 0
              ? null
              : <span className='subtext'>Items Per Page: <strong>10</strong></span>}
          </BCol>
          <BCol>
            <Pagination className='justify-content-end'>
              <Pagination.Prev onClick={() => previousPage()} disabled={!canPreviousPage} />
              {generatePagination(pageIndex + 1, pageCount).map((page) => {
                if (page === -1)
                  return <Pagination.Ellipsis key={page} onClick={() => gotoPage(pageIndex - 5)} />
                else if (page === -2)
                  return <Pagination.Ellipsis key={page} onClick={() => gotoPage(pageIndex + 5)} />
                else if (page === pageIndex + 1)
                  return <Pagination.Item key={page} active>{page}</Pagination.Item>
                else
                  return <Pagination.Item key={page} onClick={() => gotoPage(Number(page) - 1)}>{page}</Pagination.Item>
              })}
              <Pagination.Next onClick={() => nextPage()} disabled={!canNextPage} />
            </Pagination>
          </BCol>
        </BRow>
        <div className='viewall-table table'>
          {isLoading ? <div className='center-spinner mt-4'><Spinner animation="border" /></div> : null}
          <table {...getTableProps()}>
            <thead>
              {headerGroups.map((headerGroup: HeaderGroup<DsBlockObj | TxBlockObj | TransactionDetails>) => (
                <tr {...headerGroup.getHeaderGroupProps()} key={headerGroup.getHeaderGroupProps().key} >
                  {headerGroup.headers.map((column) => (
                    <th {...column.getHeaderProps()} key={column.getHeaderProps().key} id={column.id}>
                      {column.render('Header')}
                    </th>
                  ))}
                </tr>
              ))}
            </thead>
            <tbody style={isLoading ? { opacity: '0.5' } : {}}{...getTableBodyProps()}>
              {page.map((row: Row<DsBlockObj | TxBlockObj | TransactionDetails>) => {
                prepareRow(row)
                return (
                  <tr {...row.getRowProps()} key={row.getRowProps().key}>
                    {row.cells.map((cell: Cell<DsBlockObj | TxBlockObj | TransactionDetails>) => {
                      return (
                        <td {...cell.getCellProps()}
                          key={cell.getCellProps().key}>
                          {cell.render('Cell')}
                        </td>
                      )
                    })}
                  </tr>
                )
              })}
            </tbody>
          </table>
        </div>
      </>
    )
  }
Example #5
Source File: index.tsx    From livepeer-com with MIT License 4 votes vote down vote up
CommonAdminTable = ({
  id,
  loading,
  onFetchData,
  onRowSelected,
  setNextCursor,
  columns,
  data,
  nextCursor,
  err,
  filtersDesc,
  rowsPerPage,
  initialSortBy = [],
  children,
}: CommonAdminTableProps) => {
  const [cursor, setCursor] = useState("");
  const [prevCursor, setPrevCursor] = useState([]);

  const fetchDataDebounced = useAsyncDebounce(({ sortBy, cursor, filters }) => {
    let order;
    if (sortBy.length) {
      order = sortBy.map((o) => `${o.id}-${o.desc}`).join(",");
    }
    onFetchData({ order, cursor, filters });
  }, 1000);

  const dm = useMemo(() => data, [data]);

  const tableOptions: any = {
    columns,
    data: dm,
    manualFilters: true,
    autoResetSortBy: false,
    manualSortBy: true,
    maxMultiSortColCount: 2,
    initialState: { sortBy: initialSortBy },
  };

  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    prepareRow,
    selectedFlatRows,
    toggleAllRowsSelected,
    setFilter,
    state: { filters, sortBy },
    rows,
  }: any = useTable(
    tableOptions,
    useFilters,
    useSortBy,
    useRowSelect,
    (hooks) => {
      hooks.visibleColumns.push((columns) => [
        // Let's make a column for selection
        {
          id: "selection",
          // The header can use the table's getToggleAllRowsSelectedProps method
          // to render a checkbox
          Header: ({ rows }) => {
            return (
              <>
                <Button
                  variant="secondarySmall"
                  disabled={prevCursor.length === 0}
                  sx={{ margin: 0, padding: "2px", px: "4px" }}
                  onClick={() => {
                    setNextCursor(cursor);
                    setCursor(prevCursor.pop());
                    setPrevCursor([...prevCursor]);
                  }}>
                  ⭠
                </Button>
                <Button
                  variant="secondarySmall"
                  disabled={rows.length < rowsPerPage || nextCursor === ""}
                  sx={{ margin: 0, ml: 2, padding: "2px", px: "4px" }}
                  onClick={() => {
                    prevCursor.push(cursor);
                    setPrevCursor([...prevCursor]);
                    setCursor(nextCursor);
                    setNextCursor("");
                  }}>
                  ⭢
                </Button>
              </>
            );
          },
          // The cell can use the individual row's getToggleRowSelectedProps method
          // to the render a checkbox
          Cell: ({ row }) => (
            <div>
              <Checkbox
                // @ts-ignore
                value={row.isSelected}
                onClick={(e) => {
                  toggleAllRowsSelected(false);
                  // @ts-ignore
                  row.toggleRowSelected(!row.isSelected);
                }}
              />
            </div>
          ),
        },
        ...columns,
      ]);
    }
  );

  useEffect(() => {
    onRowSelected(selectedFlatRows[0]?.original);
  }, [selectedFlatRows]);

  useEffect(() => {
    setPrevCursor([]);
    setNextCursor("");
    setCursor("");
  }, [sortBy, filters]);

  useEffect(() => {
    fetchDataDebounced({ sortBy, cursor, filters });
  }, [sortBy, cursor, filters]);

  return (
    <Box
      id={id}
      sx={{
        mb: 0,
        mt: 0,
      }}>
      <Flex
        sx={{
          justifyContent: "flex-start",
          alignItems: "baseline",
          my: "1em",
        }}>
        {children}
        {filtersDesc.map((fd) => {
          if (typeof fd.render === "function") {
            return fd.render({
              value: (filters.find((o) => o.id === fd.id) || [])[0]?.value,
              setValue: (v) => setFilter(fd.id, v),
            });
          }
          return (
            <Input
              key={fd.id}
              sx={{ width: "10em", ml: "1em" }}
              label={`${fd.placeholder || fd.id} filter input`}
              value={(filters.find((o) => o.id === fd.id) || [])[0]?.value}
              onChange={(e) => setFilter(fd.id, e.target.value)}
              placeholder={fd.placeholder}></Input>
          );
        })}
      </Flex>
      {err && <Box>{err}</Box>}
      <Box>
        <Box
          as="table"
          sx={{
            display: "table",
            width: "100%",
            borderCollapse: "inherit",
            borderSpacing: "0",
            border: 0,
          }}
          {...getTableProps()}>
          <Box as="thead" sx={{ position: "relative" }}>
            {headerGroups.map((headerGroup, i) => (
              <Box as="tr" key={i} {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map((column: any, i) => (
                  <Box
                    as="th"
                    sx={{
                      userSelect: "none",
                      fontWeight: "normal",
                      textTransform: "uppercase",
                      bg: "rgba(0,0,0,.03)",
                      borderBottom: "1px solid",
                      borderTop: "1px solid",
                      borderColor: "muted",
                      borderLeft: "0px solid",
                      borderRight: "0px solid",
                      fontSize: 0,
                      color: "gray",
                      py: 2,
                      "&:first-of-type": {
                        borderLeft: "1px solid",
                        borderColor: "muted",
                        borderTopLeftRadius: 6,
                        borderBottomLeftRadius: 6,
                      },
                      "&:last-of-type": {
                        borderRight: "1px solid",
                        borderColor: "muted",
                        borderTopRightRadius: 6,
                        borderBottomRightRadius: 6,
                      },
                    }}
                    align="left"
                    {...column.getHeaderProps(
                      column.getSortByToggleProps({ title: "" })
                    )}
                    key={i}>
                    <Flex sx={{ mr: "-18px" }}>
                      {column.render("Header")}
                      <span>
                        {column.canSort &&
                          (column.isSorted
                            ? column.isSortedDesc
                              ? "⭣"
                              : "⭡"
                            : "⭥")}
                      </span>
                      {i === headerGroup.headers.length - 1 && (
                        <Flex
                          sx={{ alignItems: "center", ml: "auto", mr: "1em" }}>
                          <Flex>
                            <ReactTooltip
                              id={`tooltip-multiorder`}
                              className="tooltip"
                              place="top"
                              type="dark"
                              effect="solid">
                              To multi-sort (sort by two column simultaneously)
                              hold shift while clicking on second column name.
                            </ReactTooltip>
                            <Help
                              data-tip
                              data-for={`tooltip-multiorder`}
                              sx={{
                                cursor: "pointer",
                                ml: 1,
                              }}
                            />
                          </Flex>
                        </Flex>
                      )}
                    </Flex>
                  </Box>
                ))}
              </Box>
            ))}
            {loading && (
              <Box
                as="tr"
                sx={{
                  height: "0px",
                  border: 0,
                  bg: "transparent !important",
                  margin: 0,
                  padding: 0,
                }}>
                <Box
                  as="th"
                  sx={{ border: 0, bg: "transparent", margin: 0, padding: 0 }}
                  colSpan={1000}>
                  <Box sx={{ width: "100%", position: "relative" }}>
                    <Box
                      sx={{
                        position: "absolute",
                        top: "-1px",
                        left: "6px",
                        right: "0px",
                      }}>
                      <Box
                        sx={{
                          backgroundColor: "dodgerblue",
                          height: "1px",
                          animation: `${loadingAnim} 3s ease-in-out infinite`,
                        }}
                      />
                    </Box>
                  </Box>
                </Box>
              </Box>
            )}
          </Box>

          <tbody {...getTableBodyProps()}>
            {rows.map((row: any, rowIndex) => {
              prepareRow(row);
              return (
                <Box
                  as="tr"
                  sx={{
                    bg: "transparent !important",
                  }}
                  {...row.getRowProps()}>
                  {row.cells.map((cell) => {
                    return (
                      <Box
                        as="td"
                        sx={{
                          fontSize: 1,
                          borderBottomColor: "muted",
                          borderBottomWidth: "1px",
                          borderBottomStyle: "solid",
                          borderTop: "0px solid",
                          borderLeft: "0px solid",
                          borderRight: "0px solid",
                        }}
                        {...cell.getCellProps()}>
                        {renderCell(cell)}
                      </Box>
                    );
                  })}
                </Box>
              );
            })}
          </tbody>
        </Box>
      </Box>
    </Box>
  );
}