ketr.photos/client/src/useApi.tsx
James Ketrenos 17fbb4e21c Face exploration working even better
Signed-off-by: James Ketrenos <james_git@ketrenos.com>
2023-01-18 12:23:48 -08:00

41 lines
850 B
TypeScript

import { useState, useEffect } from 'react';
type UseApi = {
loading: boolean,
data: any,
error: any
};
const useApi = (_url: string, _options?: {}) : UseApi => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState(undefined);
const [error, setError] = useState<any>(undefined);
useEffect(() => {
if (_url === '') {
return;
}
const fetchApi = async () => {
console.log(`Fetching ${_url}...`);
try {
const res = await window.fetch(_url, _options);
const data = await res.json();
setData(data);
setLoading(false);
} catch (e) {
console.log(e);
setError(e)
setLoading(false);
};
};
fetchApi();
}, [_url, _options]);
return { loading, data, error };
};
export type { UseApi };
export { useApi };