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

89 lines
2.3 KiB
TypeScript
Raw Normal View History

import React, { 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";
import useSetTimeout from "../../utils/useSetTimeout";
import { AlertPanel, AlertType } 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);
export const AlertProvider: FunctionComponent = ({ children }) => {
const { t } = useTranslation();
2020-08-08 13:52:23 +00:00
const [alerts, setAlerts] = useState<AlertType[]>([]);
const setTimeout = useSetTimeout();
2022-03-15 09:44:46 +00:00
const createId = () => Math.random().toString(16);
2020-08-07 13:44:34 +00:00
2022-03-15 09:44:46 +00:00
const hideAlert = (key: string) => {
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
};
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;
}