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

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