keycloak-scim/src/components/alert/Alerts.tsx

39 lines
1.1 KiB
TypeScript
Raw Normal View History

import React, { useState, createContext, ReactNode, useContext } from "react";
import { AlertType, AlertPanel } from "./AlertPanel";
import { AlertVariant } from "@patternfly/react-core";
2020-08-07 13:44:34 +00:00
type AlertProps = {
addAlert: (message: string, variant?: AlertVariant) => void;
};
export const AlertContext = createContext<AlertProps>({
addAlert: () => {},
});
export const useAlerts = () => useContext(AlertContext);
export const AlertProvider = ({ children }: { children: ReactNode }) => {
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
};
const addAlert = (
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
};
return (
<AlertContext.Provider value={{ addAlert }}>
<AlertPanel alerts={alerts} onCloseAlert={hideAlert} />
{children}
</AlertContext.Provider>
);
};