Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda