Added useFetch hook. Updated database check.

This commit is contained in:
Mike Cao 2020-08-30 15:29:31 -07:00
parent 7a81dda7b6
commit d0ca0819c6
14 changed files with 146 additions and 237 deletions

39
hooks/useFetch.js Normal file
View 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 };
}