Skip to content

Instantly share code, notes, and snippets.

@sinnus
Created October 5, 2020 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinnus/0500f45a156b992ae65d385fc2d760df to your computer and use it in GitHub Desktop.
Save sinnus/0500f45a156b992ae65d385fc2d760df to your computer and use it in GitHub Desktop.
import React, { useState, useRef, ReactElement } from 'react';
import { Alert } from "react-bootstrap";
import { Variant } from "react-bootstrap/esm/types";
import { MessageErrorVO, FieldErrorVO } from '../models/MessageErrorVO';
export type AlertType = {
key: number,
message: string | string[]
variant: Variant
}
export type AlertPanelProps = {
alerts: Array<AlertType>
onCloseAlert: (key: number) => void
}
export function AlertPanel({ alerts, onCloseAlert }: AlertPanelProps) {
return (
<>
{alerts.map(({ key, variant, message }) => (
<Alert key={key} variant={variant} dismissible onClose={() => onCloseAlert(key)}>
{message instanceof Array ? (
<ul>
{message.map((value, i) => (
<li key={i}>{value}</li>
))}
</ul>
) : (<p>{message}</p>)}
</Alert>
))}
</>
)
}
export type AlertsObject = {
add(message: string | string[], variant?:Variant):void
addErrors(messageError:MessageErrorVO):void
panel():ReactElement
closeAll():void
}
export function useAlerts():AlertsObject {
const [alerts, setAlerts] = useState<Array<AlertType>>([]);
const uniqIdRef = useRef<number>(0)
const createId = () => {
let result = uniqIdRef.current
uniqIdRef.current = uniqIdRef.current + 1
return result
}
const add = (message:string | string[], variant:Variant = "info") => {
const key = createId();
setAlerts((alerts) => [...alerts, { key, message, variant }]);
}
const addErrors = (messageError:MessageErrorVO) => {
if (messageError.error != null) {
add(messageError.error, "danger")
} else if (messageError.errors != null && messageError.errors.length > 0) {
var messages:string[] = [];
for (let error of messageError.errors) {
messages.push(error.message + uniqIdRef.current);
}
add(messages, "danger")
} else {
add("Error message absent", "danger")
}
}
const closeAlert = (key: number) => {
setAlerts((alerts) => [...alerts.filter((el) => el.key !== key)]);
};
const closeAll = () => {
setAlerts([])
}
const panel = () => <AlertPanel alerts={alerts} onCloseAlert={closeAlert}/>;
return {add, addErrors, panel, closeAll};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment