0 points

Remote Table Hook


dashboard

Tue Oct 20 2020 07:22:51 GMT+0000 (UTC)

Posted by @Tony Dung #javascript #react.js

const useRemoteTable = ({ promiseFn, searchOption, defaultOrder, columnSchema = [] }) => {
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [order, setOrder] = useState(defaultOrder);
  const [reloadTimeStamp, setTimeStamp] = useState(Date.now());

  const onChange = (onChangeNest) => (pagination, filter, sorter, ...args) => {
    if (pagination.current !== page) {
      setPage(pagination.current);
    }
    if (pagination.pageSize !== limit) {
      setPage(1);
      setLimit(pagination.pageSize);
    }
    if (!isEmpty(sorter) && sorter.column) {
      const newOrder = map(columnSchema, (item, index) =>
        index === sorter.column?.columnIndex ? sorter.order : false
      );
      setOrder(newOrder);
    } else {
      setOrder(undefined);
    }
    onChangeNest(pagination, filter, sorter, ...args);
  };

  const reload = useCallback(() => {
    setTimeStamp(Date.now());
  }, []);

  useEffect(() => {
    setPage(1);
  }, [searchOption]);

  const watchWalue = useMemo(
    () => ({
      limit,
      page,
      order,
      searchOption,
      reload: reloadTimeStamp
    }),
    [limit, order, page, reloadTimeStamp, searchOption]
  );

  const { data, error, isPending } = useAsync({
    promiseFn,
    searchOption,
    watch: watchWalue,
    pagination: {
      order: getOrderFromTableToAPI(order),
      orderField: columnSchema[findIndex(order, (i) => i)],
      skip: (page - 1) * limit,
      limit
    }
  });
  return {
    loading: isPending,
    reload,
    page,
    limit,
    error,
    data,
    order,
    onChange
  };
};
content_copy Copy

combinable with promise. Update onChange function to work with different table library