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

66 lines
1.9 KiB
TypeScript
Raw Normal View History

import React, { createContext, FunctionComponent, useState } from "react";
import { useTranslation } from "react-i18next";
import { AlertVariant } from "@patternfly/react-core";
import type { AxiosError } from "axios";
import useRequiredContext from "../../utils/useRequiredContext";
import useSetTimeout from "../../utils/useSetTimeout";
import { AlertPanel, AlertType } from "./AlertPanel";
2020-08-07 13:44:34 +00:00
type AlertProps = {
addAlert: (
message: string,
variant?: AlertVariant,
description?: string
) => void;
addError: (message: string, error: any) => void;
};
export const AlertContext = createContext<AlertProps | undefined>(undefined);
export const useAlerts = () => useRequiredContext(AlertContext);
export const AlertProvider: FunctionComponent = ({ children }) => {
const { t } = useTranslation();
2020-08-08 13:52:23 +00:00
const [alerts, setAlerts] = useState<AlertType[]>([]);
const setTimeout = useSetTimeout();
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.success,
description?: string
) => {
const key = createId();
setTimeout(() => hideAlert(key), 8000);
setAlerts([{ key, message, variant, description }, ...alerts]);
2020-08-07 13:44:34 +00:00
};
const addError = (message: string, error: Error | AxiosError) => {
addAlert(
t(message, {
error:
"response" in error
2022-03-07 13:42:06 +00:00
? error.response?.data?.error_description ||
error.response?.data?.errorMessage ||
error.response?.data?.error
: error,
}),
AlertVariant.danger
);
};
return (
<AlertContext.Provider value={{ addAlert, addError }}>
<AlertPanel alerts={alerts} onCloseAlert={hideAlert} />
{children}
</AlertContext.Provider>
);
};