How do I fix the timer problem?
-
There is a problem with the timer made on react, I receive data from the server, display it in the component through props, but the timer does not work correctly on the page, every second the timer becomes null: null: null: null. That is, correct indicators alternate with an error every second. Tried getting states via Redux, same problem.
const [lobby, setLobby] = React.useState('') React.useEffect(() => { fetch(`${ENDOPOINT}/lobby/rates/${id}/`, { method: 'GET', }) .then((response) => response.json()) .then((data) => { setLobby(data) }) .catch(() => { setError(true) }) }, [isLoading]) return ( <PageTemplate> <div> <Timer date={lobby.date} /> } </div> </PageTemplate>
const [timerDays, setTimerDays] = useState('00'); const [timerHours, setTimerHours] = useState('00'); const [timerMinutes, setTimerMinutes] = useState('00'); const [timerSeconds, setTimerSeconds] = useState('00'); let interval = useRef(); const startTimer = () => { const countdownDateTrueFormat = `${props.date}`.split("+")[0] const countdownDate = new Date(countdownDateTrueFormat).getTime(); interval = setInterval(()=> { const now = new Date().getTime(); const distance = countdownDate - now; let days = Math.floor(distance / (1000 * 60 * 60 * 24)); let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); let seconds = Math.floor((distance % (1000 * 60)) / 1000); if(distance < 0) { clearInterval(interval.current) } else { setTimerDays(days) setTimerHours(hours) setTimerMinutes(minutes) setTimerSeconds(seconds) } }, 1000) } useEffect(()=> { startTimer() let someref = interval.current return ()=> { clearInterval(someref) } })
JavaScript Arabella Skinner, Mar 22, 2019
0 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!