appNotification.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { useMemo } from 'react';
  2. import { v4 as uuidv4 } from 'uuid';
  3. import { getMessageFromError } from 'app/core/utils/errors';
  4. import { AppNotification, AppNotificationSeverity, useDispatch } from 'app/types';
  5. import { notifyApp } from '../actions';
  6. const defaultSuccessNotification = {
  7. title: '',
  8. text: '',
  9. severity: AppNotificationSeverity.Success,
  10. icon: 'check',
  11. };
  12. const defaultWarningNotification = {
  13. title: '',
  14. text: '',
  15. severity: AppNotificationSeverity.Warning,
  16. icon: 'exclamation-triangle',
  17. };
  18. const defaultErrorNotification = {
  19. title: '',
  20. text: '',
  21. severity: AppNotificationSeverity.Error,
  22. icon: 'exclamation-triangle',
  23. };
  24. export const createSuccessNotification = (title: string, text = '', traceId?: string): AppNotification => ({
  25. ...defaultSuccessNotification,
  26. title,
  27. text,
  28. id: uuidv4(),
  29. timestamp: Date.now(),
  30. showing: true,
  31. });
  32. export const createErrorNotification = (
  33. title: string,
  34. text: string | Error = '',
  35. traceId?: string,
  36. component?: React.ReactElement
  37. ): AppNotification => {
  38. return {
  39. ...defaultErrorNotification,
  40. text: getMessageFromError(text),
  41. title,
  42. id: uuidv4(),
  43. traceId,
  44. component,
  45. timestamp: Date.now(),
  46. showing: true,
  47. };
  48. };
  49. export const createWarningNotification = (title: string, text = '', traceId?: string): AppNotification => ({
  50. ...defaultWarningNotification,
  51. title,
  52. text,
  53. traceId,
  54. id: uuidv4(),
  55. timestamp: Date.now(),
  56. showing: true,
  57. });
  58. /** Hook for showing toast notifications with varying severity (success, warning error).
  59. * @example
  60. * const notifyApp = useAppNotification();
  61. * notifyApp.success('Success!', 'Some additional text');
  62. * notifyApp.warning('Warning!');
  63. * notifyApp.error('Error!');
  64. */
  65. export function useAppNotification() {
  66. const dispatch = useDispatch();
  67. return useMemo(
  68. () => ({
  69. success: (title: string, text = '') => {
  70. dispatch(notifyApp(createSuccessNotification(title, text)));
  71. },
  72. warning: (title: string, text = '', traceId?: string) => {
  73. dispatch(notifyApp(createWarningNotification(title, text, traceId)));
  74. },
  75. error: (title: string, text = '', traceId?: string) => {
  76. dispatch(notifyApp(createErrorNotification(title, text, traceId)));
  77. },
  78. }),
  79. [dispatch]
  80. );
  81. }