2019-11-02 02:27:36 -07:00
|
|
|
import { useState, useEffect } from 'react';
|
|
|
|
|
2019-11-12 05:35:47 -08:00
|
|
|
export type APIResponse<T> = { status: string; data?: T };
|
|
|
|
|
|
|
|
export interface FetchState<T> {
|
|
|
|
response: APIResponse<T>;
|
|
|
|
error?: Error;
|
|
|
|
isLoading: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useFetch = <T extends {}>(url: string, options?: RequestInit): FetchState<T> => {
|
|
|
|
const [response, setResponse] = useState<APIResponse<T>>({ status: 'start fetching' });
|
|
|
|
const [error, setError] = useState<Error>();
|
|
|
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
2019-11-02 02:27:36 -07:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const fetchData = async () => {
|
|
|
|
setIsLoading(true);
|
|
|
|
try {
|
2020-01-20 07:50:32 -08:00
|
|
|
const res = await fetch(url, { cache: 'no-cache', credentials: 'same-origin', ...options });
|
2019-11-02 02:27:36 -07:00
|
|
|
if (!res.ok) {
|
|
|
|
throw new Error(res.statusText);
|
|
|
|
}
|
2019-11-12 05:35:47 -08:00
|
|
|
const json = (await res.json()) as APIResponse<T>;
|
2019-11-02 02:27:36 -07:00
|
|
|
setResponse(json);
|
|
|
|
setIsLoading(false);
|
|
|
|
} catch (error) {
|
|
|
|
setError(error);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
fetchData();
|
|
|
|
}, [url, options]);
|
|
|
|
return { response, error, isLoading };
|
|
|
|
};
|