import { useState, useEffect, useRef, useCallback } from 'react' const URL = 'https://api.chucknorris.io/jokes/random?category=dev'; export function Fetch() { // const [seconds, setSeconds] = useState(15); const [last, setLast] = useState(0); const [now, setNow] = useState(0); const [response, setResponse] = useState(undefined); const fetchRef = useRef(0); const countdownRef = useRef(0); const inputRef = useRef(null); const fetchData = async () => { setLast(Date.now()); setResponse(undefined); try { const response = await fetch(URL); if (response.ok) { const data = await response.json(); setResponse(data); } } catch (error) { console.error(error) } }; const stopFetching = () => { clearInterval(fetchRef.current); clearInterval(countdownRef.current); if (inputRef.current) { inputRef.current.disabled = false; } } const startFetching = useCallback(() => { if (inputRef.current) { stopFetching(); inputRef.current.disabled = true; fetchRef.current = setInterval(fetchData, 1000 * Number(inputRef.current.value)); countdownRef.current = setInterval(() => setNow(Date.now()), 1000); setNow(Date.now()); fetchData(); } }, []); useEffect(() => { startFetching(); return stopFetching; }, [startFetching]) const localizedLast = new Intl.DateTimeFormat('lt-LT', { dateStyle: 'short', timeStyle: 'long', }).format(last); return (
gauti kas sek. Iki sekanĨio liko {inputRef.current ? Number(inputRef.current.value) - Math.floor((now - last) / 1000) : 0} sek.

Paskutinis gavimas: {localizedLast}

{ response ? <>
{response.value}
: }
); }