The following is just to fetch the time and display it, and using a JS interval timer to invoke a function to set the state, so as to cause the first useEffect()
run again to fetch a newer time and update the screen:
export default function App() {
const [data, setData] = useState({});
const [timeID, setTimeID] = useState(0);
useEffect(() => {
fetch("https://worldtimeapi.org/api/timezone/America/Los_Angeles")
.then(res => res.json())
.then(dataFetched => {
setData(dataFetched);
});
}, [timeID]);
useEffect(() => {
setInterval(() => {
console.log("INTERVAL", timeID);
setTimeID(timeID + 1);
}, 3000);
}, []);
return (
<div className="App">
<pre className="data">
{ data.datetime }
</pre>
</div>
);
}
Example: https://codesandbox.io/s/festive-hawking-fjqnd
It is able to update once (after 3 seconds), but the console.log()
always showed timeID
being 0
. I thought the function is a closure and should be able to successfully call setTimeID()
and therefore alter the state?