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

101
Visualizações
React state adds 1 but subtracts 2

I am writing a function to like/unlike posts and add or subtract 1 from the likes total. Something isn't right as the addition works correctly (adds 1) but it subtracts 2 for some reason. I am not sure if it's to do with the state update delay.

const Post = (props: PostProps) => {
  const {
    post: {
      content,
      author,
      postedDate,
      likes,
      comments,
      shares,
      isLiked,
      isBookmarked,
    },
  } = props;

  const [isPostBookmarked, setIsPostBookmarked] = useState(isBookmarked);
  const [isPostLiked, setIsPostLiked] = useState(isLiked);
  const [likesCount, setLikesCount] = useState(likes);

  const handlePostLikeClick = () => {
    setIsPostLiked((prevIsLikedState) => {
      setLikesCount((prevLikesCountState) => {
        return prevIsLikedState
          ? prevLikesCountState - 1
          : prevLikesCountState + 1;
      });

      return !prevIsLikedState;
    });

    return (
      <IconButton
        icon={Heart}
        label={likesCount}
        filled={isPostLiked}
        onClick={handlePostLikeClick}
      />
    )
  };
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are nesting two different state updates in same function which leads to some fuzzy issues,

Can you try changing you handlePostLikeClick function to the one mentioned below??

  const handlePostLikeClick = () => {
    setLikesCount((prevLikesCountState) => {
      return isPostLiked ? prevLikesCountState - 1 : prevLikesCountState + 1;
    });
    setIsPostLiked((prevIsLikedState) => {
      return !prevIsLikedState;
    });
  };

You can use this code sandbox for reference

about 4 years ago · Juan Pablo Isaza Relatório

0

The answer given by @sumanth seems quite right, but it seems something missing. In the given answer, using same onClick function handlePostLikeClick, 2 states are going to be updated. But it should only be used to update isPostLiked. Because likesCount should be updated only if any state changes detected for isPostLiked state. Therefore, it is essential to use use effect as follows.

  const [isPostLiked, setIsPostLiked] = useState(false);
  const [likesCount, setLikesCount] = useState(1);

  useEffect(() => {
    setLikesCount((current) => (isPostLiked ? current + 1 : current - 1));
  }, [isPostLiked]);

  const handlePostLikeClick = () => {
    setIsPostLiked((prevIsLikedState) => !prevIsLikedState);
  };

Explantion

Initial state for likesCount used as 1, because during initial rendering use effect will be triggered and update likesCount to 0 (since isPostLiked initial state is false). Additionally, you can see likesCount increases its count only if isPostLiked is true.

But with @sumaneth answer, likesCount increases if isPostLiked is false.

isPostLiked ? prevLikesCountState - 1 : prevLikesCountState + 1;

Therefore, it's not tracking current change of isPostLiked state, but it's using its previous state to do the update on likesCount.

Therefore, you defenitely, need to use use effect to keep track on the current change of isPostLiked state and do the update on likesCount.

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