created new hook for sorting table data
This commit is contained in:
parent
45e88c07a9
commit
c382d9238d
35
src/hooks/useSortableData.js
Normal file
35
src/hooks/useSortableData.js
Normal 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 };
|
||||
};
|
Loading…
x
Reference in New Issue
Block a user