const useInterval = (callback, interval, immediate) => {
const ref = useRef();
useEffect(() => {
ref.current = callback;
}, [callback]);
useEffect(() => {
let cancelled = false;
const fn = () => {
ref.current(() => cancelled);
};
const id = setInterval(fn, interval);
if (immediate) fn();
return () => {
cancelled = true;
clearInterval(id);
};
}, [interval, immediate]);
};
const [temperature, setTemperature] = useState();
useInterval(async (isCancelled) => {
try {
const response = await fetch('urlToWeatherData');
if (isCancelled()) return;
if (response.status !== 200) {
throw new Error(response.statusText);
}
const [{ temperature }] = await response.json();
if (isCancelled()) return;
console.log(temperature);
setTemperature(temperature);
} catch (err) {
console.log('Fetch Error:', err);
}
}, 15000, true);