Created
October 8, 2022 12:45
-
-
Save Enigma10/cdf41a2e8d436cd0fcbfa29a4a014b5c to your computer and use it in GitHub Desktop.
Polling Time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
import "./styles.css"; | |
const TOTALTIME = 15000; | |
export default function App() { | |
const [loading, setLoading] = useState(true); | |
const [startDate, setStartDate] = useState(null); | |
function fetchApi() { | |
return "pending"; | |
} | |
// polling api | |
useEffect(() => { | |
const date = new Date(); // | |
if (!startDate) { | |
setStartDate(date.toString()); | |
} | |
const timeInterval = setInterval(async () => { | |
const newDate = new Date(); | |
const oldDate = new Date(startDate); | |
if (newDate - oldDate > TOTALTIME) { | |
clearTimeout(timeInterval); | |
setLoading(false); | |
} else { | |
const response = await fetchApi(); | |
console.log(response, "reponse"); | |
if (response === "success" || response === "error") { | |
clearInterval(timeInterval); | |
setLoading(false); | |
} | |
} | |
}, 1000); | |
return () => { | |
clearInterval(timeInterval); | |
}; | |
}, [startDate]); | |
return <div className="App">{loading ? `loading` : `Something is here`}</div>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment