feat(FE-208): enhance PurchaseTable with improved state management and memoization

This commit is contained in:
rstubryan
2025-11-18 13:35:58 +07:00
parent 2f2c1fca07
commit 9a650a130d
+78 -52
View File
@@ -1,6 +1,6 @@
'use client'; 'use client';
import { ChangeEventHandler, useState } from 'react'; import { ChangeEventHandler, useCallback, useMemo, useState } from 'react';
import useSWR from 'swr'; import useSWR from 'swr';
import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table'; import { CellContext, ColumnDef, SortingState } from '@tanstack/react-table';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
@@ -10,7 +10,6 @@ import Table from '@/components/Table';
import DebouncedTextInput from '@/components/input/DebouncedTextInput'; import DebouncedTextInput from '@/components/input/DebouncedTextInput';
import Button from '@/components/Button'; import Button from '@/components/Button';
import { useModal } from '@/components/Modal'; import { useModal } from '@/components/Modal';
import Modal from '@/components/Modal';
import ConfirmationModal from '@/components/modal/ConfirmationModal'; import ConfirmationModal from '@/components/modal/ConfirmationModal';
import SelectInput, { import SelectInput, {
OptionType, OptionType,
@@ -23,20 +22,25 @@ import RowOptionsMenuWrapper from '@/components/table/RowOptionsMenuWrapper';
import { cn, formatDate, formatCurrency } from '@/lib/helper'; import { cn, formatDate, formatCurrency } from '@/lib/helper';
import { isResponseSuccess } from '@/lib/api-helper'; import { isResponseSuccess } from '@/lib/api-helper';
import { useTableFilter } from '@/services/hooks/useTableFilter'; import { useTableFilter } from '@/services/hooks/useTableFilter';
import { ROWS_OPTIONS } from '@/config/constant'; import { ROWS_OPTIONS } from '@/config/constant';
import { Purchase } from '@/types/api/purchase/purchase'; import { Purchase } from '@/types/api/purchase/purchase';
import { PurchaseRequestApi } from '@/services/api/purchase'; import { PurchaseRequestApi } from '@/services/api/purchase';
import { SupplierApi } from '@/services/api/master-data';
// ===== INTERFACES =====
interface RowOptionsMenuProps {
type: 'dropdown' | 'collapse';
props: CellContext<Purchase, unknown>;
deleteClickHandler: () => void;
}
const RowOptionsMenu = ({ const RowOptionsMenu = ({
type = 'dropdown', type = 'dropdown',
props, props,
deleteClickHandler, deleteClickHandler,
}: { }: RowOptionsMenuProps) => {
type: 'dropdown' | 'collapse';
props: CellContext<Purchase, unknown>;
deleteClickHandler: () => void;
}) => {
return ( return (
<RowOptionsMenuWrapper type={type}> <RowOptionsMenuWrapper type={type}>
<Button <Button
@@ -78,6 +82,18 @@ const RowOptionsMenu = ({
}; };
const PurchaseTable = () => { const PurchaseTable = () => {
// ===== STATE MANAGEMENT =====
const [selectedSupplier, setSelectedSupplier] = useState<OptionType | null>(
null
);
const [isDeleteLoading, setIsDeleteLoading] = useState(false);
const [selectedPurchase, setSelectedPurchase] = useState<Purchase | null>(
null
);
const [sorting, setSorting] = useState<SortingState>([]);
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
// ===== TABLE FILTER STATE =====
const { const {
state: tableFilterState, state: tableFilterState,
updateFilter, updateFilter,
@@ -98,6 +114,17 @@ const PurchaseTable = () => {
}, },
}); });
// ===== MODAL HOOKS =====
const deleteModal = useModal();
// ===== USE SELECT HOOKS =====
const {
setInputValue: setSupplierInputValue,
options: supplierOptions,
isLoadingOptions: isLoadingSupplierOptions,
} = useSelect(SupplierApi.basePath, 'id', 'name');
// ===== API DATA FETCHING =====
const { const {
data: purchaseRequests, data: purchaseRequests,
isLoading, isLoading,
@@ -107,36 +134,15 @@ const PurchaseTable = () => {
PurchaseRequestApi.getAllFetcher PurchaseRequestApi.getAllFetcher
); );
// Modal hooks // ===== COMPUTED VALUES =====
const deleteModal = useModal(); const selectedRowIds = useMemo(
() => Object.keys(rowSelection).map((item) => parseInt(item)),
// Supplier modal [rowSelection]
const {
setInputValue: setSupplierInputValue,
options: supplierOptions,
isLoadingOptions: isLoadingSupplierOptions,
} = useSelect('/suppliers', 'id', 'name');
// Supplier value
const [selectedSupplier, setSelectedSupplier] = useState<OptionType | null>(
null
); );
// Modal loading state // ===== TABLE COLUMNS DEFINITION =====
const [isDeleteLoading, setIsDeleteLoading] = useState(false); const purchaseColumns: ColumnDef<Purchase>[] = useMemo(
() => [
// Selected purchase request for operations
const [selectedPurchase, setSelectedPurchase] = useState<Purchase | null>(
null
);
const [sorting, setSorting] = useState<SortingState>([]);
const [rowSelection, setRowSelection] = useState<Record<string, boolean>>({});
const selectedRowIds = Object.keys(rowSelection).map((item) =>
parseInt(item)
);
const purchaseColumns: ColumnDef<Purchase>[] = [
{ {
header: 'No. PR/PO', header: 'No. PR/PO',
cell: (props) => { cell: (props) => {
@@ -154,7 +160,9 @@ const PurchaseTable = () => {
header: 'Nama Pengaju', header: 'Nama Pengaju',
cell: (props) => { cell: (props) => {
const purchase = props.row.original; const purchase = props.row.original;
return purchase.created_user?.name || `User ID: ${purchase.created_by}`; return (
purchase.created_user?.name || `User ID: ${purchase.created_by}`
);
}, },
}, },
{ {
@@ -193,7 +201,8 @@ const PurchaseTable = () => {
{ {
header: 'Aksi', header: 'Aksi',
cell: (props) => { cell: (props) => {
const currentPageSize = props.table.getPaginationRowModel().rows.length; const currentPageSize =
props.table.getPaginationRowModel().rows.length;
const currentPageRows = props.table.getPaginationRowModel().flatRows; const currentPageRows = props.table.getPaginationRowModel().flatRows;
const currentRowRelativeIndex = const currentRowRelativeIndex =
currentPageRows.findIndex((r) => r.id === props.row.id) + 1; currentPageRows.findIndex((r) => r.id === props.row.id) + 1;
@@ -230,10 +239,12 @@ const PurchaseTable = () => {
); );
}, },
}, },
]; ],
[]
);
// Modal confirm click handler // ===== EVENT HANDLERS =====
const confirmationModalDeleteClickHandler = async () => { const confirmationModalDeleteClickHandler = useCallback(async () => {
setIsDeleteLoading(true); setIsDeleteLoading(true);
try { try {
@@ -241,31 +252,45 @@ const PurchaseTable = () => {
refreshPurchaseRequests(); refreshPurchaseRequests();
deleteModal.closeModal(); deleteModal.closeModal();
toast.success('Berhasil menghapus data permintaan pembelian!'); toast.success('Berhasil menghapus data permintaan pembelian!');
} catch (error) { } catch {
toast.error('Gagal menghapus data permintaan pembelian!'); toast.error('Gagal menghapus data permintaan pembelian!');
} }
setIsDeleteLoading(false); setIsDeleteLoading(false);
}; }, [selectedPurchase?.id, refreshPurchaseRequests, deleteModal]);
const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => { const searchChangeHandler: ChangeEventHandler<HTMLInputElement> = useCallback(
(e) => {
updateFilter('search', e.target.value); updateFilter('search', e.target.value);
}; },
[updateFilter]
);
const pageSizeChangeHandler = (val: OptionType | OptionType[] | null) => { const pageSizeChangeHandler = useCallback(
(val: OptionType | OptionType[] | null) => {
const newVal = val as OptionType; const newVal = val as OptionType;
setPageSize(newVal.value as number); setPageSize(newVal.value as number);
}; },
[setPageSize]
);
const poDateChangeHandler: ChangeEventHandler<HTMLInputElement> = (e) => { const poDateChangeHandler: ChangeEventHandler<HTMLInputElement> = useCallback(
(e) => {
updateFilter('poDate', e.target.value); updateFilter('poDate', e.target.value);
}; },
[updateFilter]
);
const supplierChangeHandler = (val: OptionType | OptionType[] | null) => { const supplierChangeHandler = useCallback(
(val: OptionType | OptionType[] | null) => {
setSelectedSupplier(val as OptionType); setSelectedSupplier(val as OptionType);
updateFilter('supplier', val ? ((val as OptionType).value as string) : ''); updateFilter(
}; 'supplier',
val ? ((val as OptionType).value as string) : ''
);
},
[updateFilter]
);
return ( return (
<> <>
@@ -405,6 +430,7 @@ const PurchaseTable = () => {
/> />
</div> </div>
{/* ===== MODAL COMPONENTS ===== */}
<ConfirmationModal <ConfirmationModal
ref={deleteModal.ref} ref={deleteModal.ref}
type='error' type='error'