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

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

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 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