2021-01-12 12:39:37 +00:00
|
|
|
import React, { DependencyList, useEffect, useState } from "react";
|
2020-09-01 14:51:59 +00:00
|
|
|
import { Spinner } from "@patternfly/react-core";
|
2021-02-17 21:12:25 +00:00
|
|
|
import { useErrorHandler } from "react-error-boundary";
|
|
|
|
|
2021-01-11 18:56:19 +00:00
|
|
|
import { asyncStateFetch } from "../../context/auth/AdminClient";
|
2020-08-04 12:59:41 +00:00
|
|
|
|
|
|
|
type DataLoaderProps<T> = {
|
|
|
|
loader: () => Promise<T>;
|
2021-01-12 12:39:37 +00:00
|
|
|
deps?: DependencyList;
|
|
|
|
children: ((arg: T) => any) | React.ReactNode;
|
2020-08-04 12:59:41 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export function DataLoader<T>(props: DataLoaderProps<T>) {
|
2021-01-12 12:39:37 +00:00
|
|
|
const [data, setData] = useState<T | undefined>();
|
2021-02-17 21:12:25 +00:00
|
|
|
const handleError = useErrorHandler();
|
2021-01-05 13:39:27 +00:00
|
|
|
|
2020-08-04 12:59:41 +00:00
|
|
|
useEffect(() => {
|
2021-01-11 18:56:19 +00:00
|
|
|
return asyncStateFetch(
|
2021-01-05 13:39:27 +00:00
|
|
|
() => props.loader(),
|
2021-02-17 21:12:25 +00:00
|
|
|
(result) => setData(result),
|
|
|
|
handleError
|
2021-01-05 13:39:27 +00:00
|
|
|
);
|
2021-01-12 12:39:37 +00:00
|
|
|
}, props.deps || []);
|
2020-08-04 12:59:41 +00:00
|
|
|
|
2020-08-21 00:09:05 +00:00
|
|
|
if (data) {
|
2020-08-04 12:59:41 +00:00
|
|
|
if (props.children instanceof Function) {
|
2021-01-12 12:39:37 +00:00
|
|
|
return props.children(data);
|
2020-08-04 12:59:41 +00:00
|
|
|
}
|
|
|
|
return props.children;
|
|
|
|
}
|
|
|
|
return (
|
2020-10-07 15:47:03 +00:00
|
|
|
<div className="pf-u-text-align-center">
|
2020-08-04 12:59:41 +00:00
|
|
|
<Spinner />
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|