umami/hooks/useFetch.js

53 lines
1.4 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';
export default function useFetch(url, params = {}, options = {}) {
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);
const keys = Object.keys(params)
.sort()
.map(key => params[key]);
const { update = [], onDataLoad = () => {} } = options;
async function loadData() {
try {
setLoadiing(true);
setError(null);
const time = performance.now();
2020-10-01 00:14:44 +02:00
const { data, status } = await get(url, params);
dispatch(updateQuery({ url, time: performance.now() - time, completed: Date.now() }));
setData(data);
2020-10-01 00:14:44 +02:00
setStatus(status);
onDataLoad(data);
} catch (e) {
console.error(e);
setError(e);
} finally {
setLoadiing(false);
}
}
useEffect(() => {
if (url) {
2020-08-31 23:11:30 +02:00
const { interval, delay = 0 } = options;
2020-08-31 23:11:30 +02:00
setTimeout(() => loadData(), delay);
const id = interval ? setInterval(() => loadData(), interval) : null;
return () => {
clearInterval(id);
};
}
}, [url, ...keys, ...update]);
2020-10-01 00:14:44 +02:00
return { data, status, error, loading };
}