2020-08-31 00:29:31 +02:00
|
|
|
import { useState, useEffect } from 'react';
|
2022-02-23 07:47:59 +01:00
|
|
|
import { saveQuery } from 'store/queries';
|
2022-02-23 08:52:31 +01:00
|
|
|
import useApi from './useApi';
|
2020-08-31 00:29:31 +02:00
|
|
|
|
2020-10-09 21:39:03 +02:00
|
|
|
export default function useFetch(url, options = {}, update = []) {
|
2020-11-10 06:01:53 +01:00
|
|
|
const [response, setResponse] = 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-11 07:36:55 +02:00
|
|
|
const [count, setCount] = useState(0);
|
2022-02-23 08:52:31 +01:00
|
|
|
const { get } = useApi();
|
2022-01-23 09:32:17 +01:00
|
|
|
const { params = {}, headers = {}, disabled, delay = 0, interval, onDataLoad } = options;
|
2020-08-31 00:29:31 +02:00
|
|
|
|
2020-10-11 07:36:55 +02:00
|
|
|
async function loadData(params) {
|
2020-08-31 00:29:31 +02:00
|
|
|
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();
|
2022-01-23 09:32:17 +01:00
|
|
|
|
2022-02-23 08:52:31 +01:00
|
|
|
const { data, status, ok } = await get(url, params, headers);
|
2020-09-03 01:49:14 +02:00
|
|
|
|
2022-02-23 07:47:59 +01:00
|
|
|
await saveQuery(url, { time: performance.now() - time, completed: Date.now() });
|
2020-09-03 01:49:14 +02:00
|
|
|
|
2020-10-04 07:36:51 +02:00
|
|
|
if (status >= 400) {
|
|
|
|
setError(data);
|
2020-11-10 06:01:53 +01:00
|
|
|
setResponse({ data: null, status, ok });
|
2020-10-04 07:36:51 +02:00
|
|
|
} else {
|
2020-11-10 06:01:53 +01:00
|
|
|
setResponse({ data, status, ok });
|
2020-10-04 07:36:51 +02:00
|
|
|
}
|
|
|
|
|
2020-10-09 21:39:03 +02:00
|
|
|
onDataLoad?.(data);
|
2020-08-31 00:29:31 +02:00
|
|
|
} 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(() => {
|
2020-10-09 08:26:05 +02:00
|
|
|
if (url && !disabled) {
|
2020-10-11 07:36:55 +02:00
|
|
|
const id = setTimeout(() => loadData(params), delay);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
clearTimeout(id);
|
|
|
|
};
|
2020-10-09 21:39:03 +02:00
|
|
|
}
|
2020-10-11 07:36:55 +02:00
|
|
|
}, [url, !!disabled, count, ...update]);
|
2020-08-31 00:29:31 +02:00
|
|
|
|
2020-10-09 21:39:03 +02:00
|
|
|
useEffect(() => {
|
2020-10-11 07:36:55 +02:00
|
|
|
if (interval && !disabled) {
|
|
|
|
const id = setInterval(() => setCount(state => state + 1), interval);
|
2020-08-31 00:29:31 +02:00
|
|
|
|
2020-10-11 07:36:55 +02:00
|
|
|
return () => {
|
|
|
|
clearInterval(id);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}, [interval, !!disabled]);
|
2020-08-31 00:29:31 +02:00
|
|
|
|
2020-11-10 06:01:53 +01:00
|
|
|
return { ...response, error, loading };
|
2020-08-31 00:29:31 +02:00
|
|
|
}
|