2020-08-31 00:29:31 +02:00
|
|
|
import { useState, useEffect } from 'react';
|
2020-09-03 01:49:14 +02:00
|
|
|
import { useDispatch } from 'react-redux';
|
2020-08-31 00:29:31 +02:00
|
|
|
import { get } from 'lib/web';
|
2020-09-03 01:49:14 +02:00
|
|
|
import { updateQuery } from 'redux/actions/queries';
|
2020-08-31 00:29:31 +02:00
|
|
|
|
|
|
|
export default function useFetch(url, params = {}, options = {}) {
|
2020-09-03 01:49:14 +02:00
|
|
|
const dispatch = useDispatch();
|
2020-08-31 00:29:31 +02:00
|
|
|
const [data, setData] = useState();
|
|
|
|
const [error, setError] = useState();
|
|
|
|
const keys = Object.keys(params)
|
|
|
|
.sort()
|
|
|
|
.map(key => params[key]);
|
|
|
|
const { update = [], onDataLoad = () => {} } = options;
|
|
|
|
|
|
|
|
async function loadData() {
|
|
|
|
try {
|
|
|
|
setError(null);
|
2020-09-03 01:49:14 +02:00
|
|
|
const time = performance.now();
|
2020-08-31 00:29:31 +02:00
|
|
|
const data = await get(url, params);
|
2020-09-03 01:49:14 +02:00
|
|
|
|
|
|
|
dispatch(updateQuery({ url, time: performance.now() - time, completed: Date.now() }));
|
|
|
|
|
2020-08-31 00:29:31 +02:00
|
|
|
setData(data);
|
|
|
|
onDataLoad(data);
|
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
|
|
|
setError(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (url) {
|
2020-08-31 23:11:30 +02:00
|
|
|
const { interval, delay = 0 } = options;
|
2020-08-31 00:29:31 +02:00
|
|
|
|
2020-08-31 23:11:30 +02:00
|
|
|
setTimeout(() => loadData(), delay);
|
2020-08-31 00:29:31 +02:00
|
|
|
|
|
|
|
const id = interval ? setInterval(() => loadData(), interval) : null;
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
clearInterval(id);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}, [url, ...keys, ...update]);
|
|
|
|
|
2020-08-31 12:53:39 +02:00
|
|
|
return { data, error, loadData };
|
2020-08-31 00:29:31 +02:00
|
|
|
}
|