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-10-01 07:34:16 +02:00
|
|
|
import { useRouter } from 'next/router';
|
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();
|
2020-10-01 00:14:44 +02:00
|
|
|
const [status, setStatus] = useState();
|
2020-08-31 00:29:31 +02:00
|
|
|
const [error, setError] = useState();
|
2020-09-20 20:28:38 +02:00
|
|
|
const [loading, setLoadiing] = useState(false);
|
2020-10-01 07:34:16 +02:00
|
|
|
const { basePath } = useRouter();
|
2020-08-31 00:29:31 +02:00
|
|
|
const keys = Object.keys(params)
|
|
|
|
.sort()
|
|
|
|
.map(key => params[key]);
|
|
|
|
const { update = [], onDataLoad = () => {} } = options;
|
|
|
|
|
|
|
|
async function loadData() {
|
|
|
|
try {
|
2020-09-20 20:28:38 +02:00
|
|
|
setLoadiing(true);
|
2020-08-31 00:29:31 +02:00
|
|
|
setError(null);
|
2020-09-03 01:49:14 +02:00
|
|
|
const time = performance.now();
|
2020-10-01 07:34:16 +02:00
|
|
|
const { data, status } = await get(`${basePath}${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);
|
2020-10-01 00:14:44 +02:00
|
|
|
setStatus(status);
|
2020-08-31 00:29:31 +02:00
|
|
|
onDataLoad(data);
|
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
|
|
|
setError(e);
|
2020-09-20 20:28:38 +02:00
|
|
|
} finally {
|
|
|
|
setLoadiing(false);
|
2020-08-31 00:29:31 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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-10-01 00:14:44 +02:00
|
|
|
return { data, status, error, loading };
|
2020-08-31 00:29:31 +02:00
|
|
|
}
|