forked from umami-software/umami
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFetch.js
62 lines (52 loc) · 1.68 KB
/
useFetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useRouter } from 'next/router';
import { get } from 'lib/web';
import { updateQuery } from 'redux/actions/queries';
export default function useFetch(url, options = {}, update = []) {
const dispatch = useDispatch();
const [response, setResponse] = useState();
const [error, setError] = useState();
const [loading, setLoadiing] = useState(false);
const [count, setCount] = useState(0);
const { basePath } = useRouter();
const { params = {}, disabled, headers, delay = 0, interval, onDataLoad } = options;
async function loadData(params) {
try {
setLoadiing(true);
setError(null);
const time = performance.now();
const { data, status, ok } = await get(`${basePath}${url}`, params, headers);
dispatch(updateQuery({ url, time: performance.now() - time, completed: Date.now() }));
if (status >= 400) {
setError(data);
setResponse({ data: null, status, ok });
} else {
setResponse({ data, status, ok });
}
onDataLoad?.(data);
} catch (e) {
console.error(e);
setError(e);
} finally {
setLoadiing(false);
}
}
useEffect(() => {
if (url && !disabled) {
const id = setTimeout(() => loadData(params), delay);
return () => {
clearTimeout(id);
};
}
}, [url, !!disabled, count, ...update]);
useEffect(() => {
if (interval && !disabled) {
const id = setInterval(() => setCount(state => state + 1), interval);
return () => {
clearInterval(id);
};
}
}, [interval, !!disabled]);
return { ...response, error, loading };
}