created new hook for sorting table data

This commit is contained in:
Pramod Mahajan 2025-05-27 22:18:44 +05:30
parent 45e88c07a9
commit c382d9238d

View File

@ -0,0 +1,35 @@
import { useState, useMemo } from 'react';
export const useSortableData = (items, config = null) => {
const [sortConfig, setSortConfig] = useState(config);
const sortedItems = useMemo(() => {
let sortableItems = [...items];
if (sortConfig !== null) {
sortableItems.sort((a, b) => {
const aValue = sortConfig.key(a).toLowerCase();
const bValue = sortConfig.key(b).toLowerCase();
if (aValue < bValue) return sortConfig.direction === 'asc' ? -1 : 1;
if (aValue > bValue) return sortConfig.direction === 'asc' ? 1 : -1;
return 0;
});
}
return sortableItems;
}, [items, sortConfig]);
const requestSort = (keyFn) => {
let direction = 'asc';
if (
sortConfig &&
sortConfig.key.toString() === keyFn.toString() &&
sortConfig.direction === 'asc'
) {
direction = 'desc';
}
setSortConfig({ key: keyFn, direction });
};
return { items: sortedItems, requestSort, sortConfig };
};