2020-09-01 14:51:59 +00:00
|
|
|
import React, { useEffect, useState } from "react";
|
|
|
|
import { Spinner } from "@patternfly/react-core";
|
2021-01-05 13:39:27 +00:00
|
|
|
import { useFetch } from "../../context/auth/AdminClient";
|
2020-08-04 12:59:41 +00:00
|
|
|
|
|
|
|
type DataLoaderProps<T> = {
|
|
|
|
loader: () => Promise<T>;
|
|
|
|
deps?: any[];
|
2020-10-06 11:56:06 +00:00
|
|
|
children: ((arg: Result<T>) => any) | React.ReactNode;
|
|
|
|
};
|
|
|
|
|
|
|
|
type Result<T> = {
|
|
|
|
data: T;
|
|
|
|
refresh: () => void;
|
2020-08-04 12:59:41 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export function DataLoader<T>(props: DataLoaderProps<T>) {
|
|
|
|
const [data, setData] = useState<{ result: T } | undefined>(undefined);
|
2021-01-05 13:39:27 +00:00
|
|
|
|
|
|
|
const [key, setKey] = useState(0);
|
|
|
|
const refresh = () => setKey(new Date().getTime());
|
|
|
|
|
2020-08-04 12:59:41 +00:00
|
|
|
useEffect(() => {
|
2021-01-05 13:39:27 +00:00
|
|
|
return useFetch(
|
|
|
|
() => props.loader(),
|
|
|
|
(result) => setData({ result })
|
|
|
|
);
|
|
|
|
}, [key]);
|
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) {
|
2020-10-06 11:56:06 +00:00
|
|
|
return props.children({
|
|
|
|
data: data.result,
|
2021-01-05 13:39:27 +00:00
|
|
|
refresh: refresh,
|
2020-10-06 11:56:06 +00:00
|
|
|
});
|
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>
|
|
|
|
);
|
|
|
|
}
|