I have a state that contains the order of the sorting. When I press a button, I want to toggle the sorting order, from -1 to 1 and back.
const [order, setOrder] = React.useState(1);
function handleSort(elementIndex) {
let firstSort = -1;
let secondSort = 1;
setContent((prev) => {
prev.sort((line1, line2) => {
return line1.props.children[elementIndex].props.children >
line2.props.children[elementIndex].props.children
? firstSort * order
: secondSort * order;
});
console.log(prev);
return [...prev];
});
setOrder((prev) => prev * -1);
}
<button
onClick={() => {
handleSort(
temporaryHeadersArrayCopy.findIndex(
(elem) => elem === element
)
);
}}
>
This is just a fraction of the code, but the main problem is that the order never modifies. I tried console logging, but from what I have read, it does not change immediately because it is a callback and it works async.
Thank you!
I'm not entirely sure what you want to do with this code. But you have an array you want to sort, based on an index. Am I right?
I would use useMemo, with the actual array and the index as dependencies. This should ensure that your sorted array updates whenever one of the dependencies change.