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

98 lines
2.2 KiB
TypeScript
Raw Normal View History

import { createContext, FunctionComponent, useState } from "react";
import { useTranslation } from "react-i18next";
import { AlertVariant } from "@patternfly/react-core";
2022-05-10 09:50:00 +00:00
import axios from "axios";
import type { AxiosError } from "axios";
import useRequiredContext from "../../utils/useRequiredContext";
2022-07-13 10:17:21 +00:00
import { AlertPanel } from "./AlertPanel";
2020-08-07 13:44:34 +00:00
export type AddAlertFunction = (
message: string,
variant?: AlertVariant,
description?: string
) => void;
export type AddErrorFunction = (message: string, error: any) => void;
type AlertProps = {
addAlert: AddAlertFunction;
addError: AddErrorFunction;
};
export const AlertContext = createContext<AlertProps | undefined>(undefined);
export const useAlerts = () => useRequiredContext(AlertContext);
2022-07-13 10:17:21 +00:00
export type AlertType = {
id: number;
message: string;
variant: AlertVariant;
description?: string;
};
export const AlertProvider: FunctionComponent = ({ children }) => {
const { t } = useTranslation();
2020-08-08 13:52:23 +00:00
const [alerts, setAlerts] = useState<AlertType[]>([]);
2020-08-07 13:44:34 +00:00
2022-07-13 10:17:21 +00:00
const hideAlert = (id: number) => {
setAlerts((alerts) => alerts.filter((alert) => alert.id !== id));
2020-08-07 13:44:34 +00:00
};
const addAlert = (
message: string,
variant: AlertVariant = AlertVariant.success,
description?: string
) => {
2022-07-13 10:17:21 +00:00
setAlerts([
{
id: Math.random(),
message,
variant,
description,
},
...alerts,
]);
2020-08-07 13:44:34 +00:00
};
2022-05-10 09:50:00 +00:00
const addError = (message: string, error: Error | AxiosError | string) => {
addAlert(
t(message, {
2022-05-10 09:50:00 +00:00
error: getErrorMessage(error),
}),
AlertVariant.danger
);
};
return (
<AlertContext.Provider value={{ addAlert, addError }}>
<AlertPanel alerts={alerts} onCloseAlert={hideAlert} />
{children}
</AlertContext.Provider>
);
};
2022-05-10 09:50:00 +00:00
function getErrorMessage(
error: Error | AxiosError<Record<string, unknown>> | string
) {
if (typeof error === "string") {
return error;
}
if (!axios.isAxiosError(error)) {
return error.message;
}
const responseData = error.response?.data ?? {};
for (const key of ["error_description", "errorMessage", "error"]) {
const value = responseData[key];
if (typeof value === "string") {
return value;
}
}
return error.message;
}