useAlert.tsx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import React from "react";
  2. const AlertContext = React.createContext(null);
  3. export function AlertProvider(props: null) {
  4. const [open, setOpen] = React.useState(false);
  5. const [position, setPosition] = React.useState({
  6. vertical: "bottom",
  7. horizontal: "right",
  8. });
  9. const [severity, setSeverity] = React.useState("info");
  10. const [message, setMessage] = React.useState("");
  11. React.useEffect(() => {
  12. let mounted = true;
  13. if (mounted) {
  14. setTimeout(() => {
  15. setOpen(false);
  16. }, 5000);
  17. }
  18. return () => {
  19. mounted = false;
  20. };
  21. }, [open]);
  22. const showAlert = React.useCallback(
  23. ({ message, severity = "info", position = null }) => {
  24. setOpen(true);
  25. setMessage(message);
  26. setSeverity(severity);
  27. if (position) setPosition(position);
  28. },
  29. []
  30. );
  31. const memData = React.useMemo(() => {
  32. return {
  33. open,
  34. position,
  35. severity,
  36. message,
  37. showAlert,
  38. };
  39. }, [open, position, severity, message, showAlert]);
  40. return <AlertContext.Provider value={memData} {...props} />;
  41. }
  42. export function useAlert() {
  43. const context = React.useContext(AlertContext);
  44. if (!context) {
  45. // eslint-disable-next-line no-throw-literal
  46. throw "error: alert context not defined.";
  47. }
  48. return context;
  49. }