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

184
Visualizações
React useEffect default value does not update properly

I am getting the property endDate from a redux store and I am sure that the property is not null or undefined, but then again the state keeps it's previous displayed value until the page is refreshed. I want the page to automatically set the state of timeLeft to millisecondsToTime(now, endDate) by default, but currently it fails, despite working after reload.

import React, { FC, useEffect, useState } from "react";
import { millisecondsToTime } from "src/utils/helpers";

import {
  StyledCountdownTimer,
  StyledTimeBox,
  StyledTimeBoxNumbers,
  StyledTimeBoxText
} from "./StyledCountdownTimer";
import { getActiveCampaign } from "../../reduxStore";

export interface CountdownTimerProps {
  endDate?: string;
}

const CountdownTimer: FC<CountdownTimerProps> = ({ endDate }) => {
  const now = Date.now();
  const [timeLeft, setTimeLeft] = useState(millisecondsToTime(now, endDate));

  const data = getActiveCampaign();

  console.log(data);

  useEffect(() => {
    const timer = setTimeout(() => {
      setTimeLeft(millisecondsToTime(now, endDate));
    }, 1000);

    if (timeLeft.finished) {
      clearTimeout(timer);
    }

    return () => {
      clearTimeout(timer);
    };
  }, [endDate, now, timeLeft.finished]);

  return (
    <StyledCountdownTimer>
      {endDate}
      {timeLeft.days}
      {millisecondsToTime(now, endDate).days}
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.days}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Days</StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.hours}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Hours</StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.minutes}</StyledTimeBoxNumbers>
        <StyledTimeBoxText></StyledTimeBoxText>
      </StyledTimeBox>
      <StyledTimeBox>
        <StyledTimeBoxNumbers>{timeLeft.seconds}</StyledTimeBoxNumbers>
        <StyledTimeBoxText>Seconds</StyledTimeBoxText>
      </StyledTimeBox>
    </StyledCountdownTimer>
  );
};

export { CountdownTimer };
about 4 years ago · Juan Pablo Isaza
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