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

222
Vistas
React how can I change a state based on a different state, in the same function
import React, {useState, useEffect} from 'react';
  
 
const Test = ( {numar}) => { 
    const [likeStatus, setLikeStatus] = useState(true);
    const [likeNumber, setLikeNumber] = useState(100);
 
    const onLikeHandler = () => { 
        setLikeStatus(prevState => !prevState);
        if(likeStatus){
            setLikeNumber(prevState=> prevState +1)
        } else {
            setLikeNumber(prevState=>prevState-1);
        }
    }
 
    console.log(likeStatus);
    console.log(likeNumber);
 
    return <button className={`like ${likeStatus ? 'liked' : ""}`} onClick={onLikeHandler}>{`Like | ${ likeNumber}`}</button>
}
 
export default Test;

I am trying to make a like button that likes/unlikes based on the click.

How can I make the second change state function wait for my first state function to finish? I tried using an use effect hook, and I am using the likeStatus in the dependecy array, but for some reason "the unlike" function triggers twice upon refresh"

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

State update is async, and state is being accessed from closure which recreates only after rerender - meaning you can not set state and then in next line to expect that you will get that new state immediately, you will get new state but only in next function call(after element rerenders). Solution is to preserve new state in temp variable.

Rewrite to this:

    const onLikeHandler = () => {
    const newLikeStatus = !likeStatus; // Here you are preserving that new state in temp variable
    setLikeStatus(newLikeStatus);

    if(newLikeStatus){
        setLikeNumber(prevState=> prevState +1)
    } else {
        setLikeNumber(prevState=>prevState-1);

    }


}
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