Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
React state does not toggle on click

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!