mirror of
https://github.com/umami-software/umami.git
synced 2025-12-08 05:12:36 +01:00
Added useFetch hook. Updated database check.
This commit is contained in:
parent
7a81dda7b6
commit
d0ca0819c6
14 changed files with 146 additions and 237 deletions
39
hooks/useFetch.js
Normal file
39
hooks/useFetch.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import { get } from 'lib/web';
|
||||
|
||||
export default function useFetch(url, params = {}, options = {}) {
|
||||
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);
|
||||
const data = await get(url, params);
|
||||
setData(data);
|
||||
onDataLoad(data);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
setError(e);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (url) {
|
||||
const { interval } = options;
|
||||
|
||||
loadData();
|
||||
|
||||
const id = interval ? setInterval(() => loadData(), interval) : null;
|
||||
|
||||
return () => {
|
||||
clearInterval(id);
|
||||
};
|
||||
}
|
||||
}, [url, ...keys, ...update]);
|
||||
|
||||
return { data, error };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue