41 lines
850 B
TypeScript
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 }; |