prometheus/web/ui/react-app/src/utils/useFetch.ts
Boyko 8a9509b0a8 Replace fetching hooks with class render prop component (#6267)
* replace fetching hooks with class render prop component

Signed-off-by: Boyko Lalov <boyskila@gmail.com>
Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* rename Fetcher

Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* status page markup separated from fetcher component

Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* fetch api reusability

Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* extract Config and Flags pages as 'dumb' components

Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* more components splitting

Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* implement fetchWithstatus HOC

Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* refactor changed files tests

Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* switching back to hooks.

Signed-off-by: blalov <boyko.lalov@tick42.com>
Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* fetch response bug fix

Signed-off-by: Boyko Lalov <boyskila@gmail.com>

* make wrapped by withstatusIndicator components names consistent

Signed-off-by: Boyko Lalov <boyskila@gmail.com>
2019-11-12 14:35:47 +01:00

35 lines
983 B
TypeScript

import { useState, useEffect } from 'react';
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);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
const res = await fetch(url, options);
if (!res.ok) {
throw new Error(res.statusText);
}
const json = (await res.json()) as APIResponse<T>;
setResponse(json);
setIsLoading(false);
} catch (error) {
setError(error);
}
};
fetchData();
}, [url, options]);
return { response, error, isLoading };
};