Reputation: 445
I'm trying to implement this table-sorting solution into an application I am working on. Here is the working codesandbox with the sorting feature I am trying to implement: https://codesandbox.io/s/table-sorting-gxt7g?file=/src/App.js
However, when I try to implement this solution in my app, I get the error:
TypeError: items is not iterable
which points to the line containing let sortableItems = [...items]
.
I get this error whether or not I initialize items as an empty array:
const useSortableData = (items = [], config = null) => {
...or how I have it below.
I am trying to pass myArrayOfObjects
to useSortableData()
.
Anyone see what I am doing wrong?
I should mention this is based on an example in this article: https://www.smashingmagazine.com/2020/03/sortable-tables-react/
const useSortableData = (items, config = null) => {
const [sortConfig, setSortConfig] = useState(config);
const sortedItems = useMemo(() => {
let sortableItems = [...items];
if (sortConfig !== null) {
sortableItems.sort((a, b) => {
if (a[sortConfig.key] < b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? -1 : 1;
}
if (a[sortConfig.key] > b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? 1 : -1;
}
return 0;
});
}
return sortableItems;
}, [items, sortConfig]);
const requestSort = (key) => {
let direction = 'ascending';
if (
sortConfig &&
sortConfig.key === key &&
sortConfig.direction === 'ascending'
) {
direction = 'descending';
}
setSortConfig({ key, direction });
};
return { items: sortedItems, requestSort, sortConfig };
};
const { items, requestSort, sortConfig } = useSortableData({ myArrayOfObjects });
const getClassNamesFor = (id) => {
if (!sortConfig) {
return;
}
return sortConfig.key === id ? sortConfig.direction : undefined;
};
Upvotes: 1
Views: 1671
Reputation: 445
Thanks, Taki. That did it!
const useSortableData = (items, config = null) => {
const [sortConfig, setSortConfig] = useState(config);
const sortedItems = useMemo(() => {
let sortableItems = [...items];
if (sortConfig !== null) {
sortableItems.sort((a, b) => {
if (a[sortConfig.key] < b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? -1 : 1;
}
if (a[sortConfig.key] > b[sortConfig.key]) {
return sortConfig.direction === 'ascending' ? 1 : -1;
}
return 0;
});
}
return sortableItems;
}, [items, sortConfig]);
const requestSort = (key) => {
let direction = 'ascending';
if (
sortConfig &&
sortConfig.key === key &&
sortConfig.direction === 'ascending'
) {
direction = 'descending';
}
setSortConfig({ key, direction });
};
return { items: sortedItems, requestSort, sortConfig };
};
const { items, requestSort, sortConfig } = useSortableData(myArrayOfObjects);
const getClassNamesFor = (id) => {
if (!sortConfig) {
return;
}
return sortConfig.key === id ? sortConfig.direction : undefined;
};
Upvotes: 1