umami/hooks/useFetch.js

58 lines
1.5 KiB
JavaScript
Raw Normal View History

import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { get } from 'lib/web';
import { updateQuery } from 'redux/actions/queries';
2020-10-01 07:34:16 +02:00
import { useRouter } from 'next/router';
2020-10-09 21:39:03 +02:00
export default function useFetch(url, options = {}, update = []) {
const dispatch = useDispatch();
const [data, setData] = useState();
2020-10-01 00:14:44 +02:00
const [status, setStatus] = useState();
const [error, setError] = useState();
const [loading, setLoadiing] = useState(false);
2020-10-01 07:34:16 +02:00
const { basePath } = useRouter();
2020-10-09 21:39:03 +02:00
const { params, disabled, headers, interval, delay = 0, onDataLoad } = options;
async function loadData() {
try {
setLoadiing(true);
setError(null);
const time = performance.now();
2020-10-09 08:26:05 +02:00
const { data, status } = await get(`${basePath}${url}`, params, headers);
dispatch(updateQuery({ url, time: performance.now() - time, completed: Date.now() }));
if (status >= 400) {
setError(data);
setData(null);
} else {
setData(data);
}
2020-10-01 00:14:44 +02:00
setStatus(status);
2020-10-09 21:39:03 +02:00
onDataLoad?.(data);
} catch (e) {
console.error(e);
setError(e);
} finally {
setLoadiing(false);
}
}
useEffect(() => {
2020-10-09 08:26:05 +02:00
if (url && !disabled) {
2020-08-31 23:11:30 +02:00
setTimeout(() => loadData(), delay);
2020-10-09 21:39:03 +02:00
}
}, [url, disabled, ...update]);
2020-10-09 21:39:03 +02:00
useEffect(() => {
const id = interval ? setInterval(() => loadData(), interval) : null;
2020-10-09 21:39:03 +02:00
return () => {
clearInterval(id);
};
}, [interval, params]);
2020-10-01 00:14:44 +02:00
return { data, status, error, loading };
}