2020-09-15 19:44:28 +00:00
|
|
|
import React, { useState, ReactElement } from "react";
|
|
|
|
import { AlertType, AlertPanel } from "./AlertPanel";
|
2020-09-01 14:51:59 +00:00
|
|
|
import { AlertVariant } from "@patternfly/react-core";
|
2020-08-07 13:44:34 +00:00
|
|
|
|
|
|
|
export function useAlerts(): [
|
2020-09-15 19:44:28 +00:00
|
|
|
(message: string, type?: AlertVariant) => void,
|
|
|
|
() => ReactElement,
|
|
|
|
(key: number) => void,
|
|
|
|
AlertType[]
|
2020-08-07 13:44:34 +00:00
|
|
|
] {
|
2020-08-08 13:52:23 +00:00
|
|
|
const [alerts, setAlerts] = useState<AlertType[]>([]);
|
2020-08-07 13:44:34 +00:00
|
|
|
const createId = () => new Date().getTime();
|
|
|
|
|
|
|
|
const hideAlert = (key: number) => {
|
2020-08-08 13:52:23 +00:00
|
|
|
setAlerts((alerts) => [...alerts.filter((el) => el.key !== key)]);
|
2020-08-07 13:44:34 +00:00
|
|
|
};
|
|
|
|
|
2020-09-15 19:44:28 +00:00
|
|
|
const add = (
|
|
|
|
message: string,
|
|
|
|
variant: AlertVariant = AlertVariant.default
|
|
|
|
) => {
|
2020-08-07 13:44:34 +00:00
|
|
|
const key = createId();
|
2020-08-08 13:52:23 +00:00
|
|
|
setAlerts([...alerts, { key, message, variant }]);
|
|
|
|
setTimeout(() => hideAlert(key), 8000);
|
2020-08-07 13:44:34 +00:00
|
|
|
};
|
|
|
|
|
2020-09-15 19:44:28 +00:00
|
|
|
const Panel = () => <AlertPanel alerts={alerts} onCloseAlert={hideAlert} />;
|
|
|
|
|
|
|
|
return [add, Panel, hideAlert, alerts];
|
2020-08-07 13:44:34 +00:00
|
|
|
}
|