()
| 67 | * @returns The current notifications state and action callbacks. |
| 68 | */ |
| 69 | export const useNotifications = (): NotificationsState => { |
| 70 | const [status, setStatus] = useState<Status>('success'); |
| 71 | const [globalError, setGlobalError] = useState<GitifyError>(); |
| 72 | |
| 73 | const [notifications, setNotifications] = useState<AccountNotifications[]>( |
| 74 | [], |
| 75 | ); |
| 76 | |
| 77 | const notificationCount = getNotificationCount(notifications); |
| 78 | |
| 79 | const unreadNotificationCount = getUnreadNotificationCount(notifications); |
| 80 | |
| 81 | const hasNotifications = useMemo( |
| 82 | () => notificationCount > 0, |
| 83 | [notificationCount], |
| 84 | ); |
| 85 | |
| 86 | const hasUnreadNotifications = useMemo( |
| 87 | () => unreadNotificationCount > 0, |
| 88 | [unreadNotificationCount], |
| 89 | ); |
| 90 | |
| 91 | const removeAccountNotifications = useCallback( |
| 92 | async (account: Account) => { |
| 93 | setStatus('loading'); |
| 94 | |
| 95 | const accountUUID = getAccountUUID(account); |
| 96 | const updatedNotifications = notifications.filter( |
| 97 | (notification) => getAccountUUID(notification.account) !== accountUUID, |
| 98 | ); |
| 99 | |
| 100 | setNotifications(updatedNotifications); |
| 101 | |
| 102 | setStatus('success'); |
| 103 | }, |
| 104 | [notifications], |
| 105 | ); |
| 106 | |
| 107 | const isFetchingRef = useRef(false); |
| 108 | const fetchNotifications = useCallback( |
| 109 | async (state: GitifyState) => { |
| 110 | if (isFetchingRef.current) { |
| 111 | // Prevent overlapping fetches |
| 112 | return; |
| 113 | } |
| 114 | isFetchingRef.current = true; |
| 115 | setStatus('loading'); |
| 116 | try { |
| 117 | const previousNotifications = notifications; |
| 118 | const fetchedNotifications = await getAllNotifications(state); |
| 119 | setNotifications(fetchedNotifications); |
| 120 | |
| 121 | // Set Global Error if all accounts have the same error |
| 122 | const allAccountsHaveErrors = |
| 123 | doesAllAccountsHaveErrors(fetchedNotifications); |
| 124 | const allAccountErrorsAreSame = |
| 125 | areAllAccountErrorsSame(fetchedNotifications); |
| 126 |
no test coverage detected