Skip to content

Instantly share code, notes, and snippets.

@Enigma10
Created October 8, 2022 12:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Enigma10/cdf41a2e8d436cd0fcbfa29a4a014b5c to your computer and use it in GitHub Desktop.
Save Enigma10/cdf41a2e8d436cd0fcbfa29a4a014b5c to your computer and use it in GitHub Desktop.
Polling Time
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