Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

88
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda