| 1 |
import { Fragment, useEffect, useState } from 'react'; |
| 2 |
import { Alert, AlertGroup, AlertVariant, ToggleGroup, ToggleGroupItem } from '@patternfly/react-core'; |
| 3 |
|
| 4 |
interface AlertInfo { |
| 5 |
title: string; |
| 6 |
variant: AlertVariant; |
| 7 |
key: number; |
| 8 |
} |
| 9 |
|
| 10 |
export const AsyncLiveRegionAlert: React.FunctionComponent = () => { |
| 11 |
const [alerts, setAlerts] = useState<AlertInfo[]>([]); |
| 12 |
const [isActive, setIsActive] = useState(false); |
| 13 |
const getUniqueId: () => number = () => new Date().getTime(); |
| 14 |
|
| 15 |
const addAlert = (alertInfo: AlertInfo) => { |
| 16 |
setAlerts((prevAlertInfo) => [alertInfo, ...prevAlertInfo]); |
| 17 |
}; |
| 18 |
|
| 19 |
useEffect(() => { |
| 20 |
let timer = null; |
| 21 |
if (isActive) { |
| 22 |
timer = setInterval(() => { |
| 23 |
addAlert({ |
| 24 |
title: `Async alert number ${alerts.length + 1}`, |
| 25 |
variant: AlertVariant.info, |
| 26 |
key: getUniqueId() |
| 27 |
}); |
| 28 |
}, 4500); |
| 29 |
} else { |
| 30 |
clearInterval(timer); |
| 31 |
} |
| 32 |
|
| 33 |
return () => { |
| 34 |
clearInterval(timer); |
| 35 |
}; |
| 36 |
}, [isActive, alerts]); |
| 37 |
|
| 38 |
return ( |
| 39 |
<Fragment> |
| 40 |
<ToggleGroup aria-label="Toggle asynchronous alerts"> |
| 41 |
<ToggleGroupItem |
| 42 |
text="Async alerts on" |
| 43 |
buttonId="async-alerts-on" |
| 44 |
isSelected={isActive} |
| 45 |
onChange={() => setIsActive(!isActive)} |
| 46 |
/> |
| 47 |
</ToggleGroup> |
| 48 |
<AlertGroup hasAnimations isLiveRegion> |
| 49 |
{alerts.map(({ title, variant, key }) => ( |
| 50 |
<Alert variant={variant} title={title} key={key} /> |
| 51 |
))} |
| 52 |
</AlertGroup> |
| 53 |
</Fragment> |
| 54 |
); |
| 55 |
}; |