|
| 1 | +import { FormattedMessage } from '@edx/frontend-platform/i18n'; |
| 2 | +import { Icon } from '@openedx/paragon'; |
| 3 | +import { NotificationsNone } from '@openedx/paragon/icons'; |
| 4 | +import React from 'react'; |
| 5 | +import messages from './messages'; |
| 6 | + |
| 7 | +interface HooKType { |
| 8 | + notificationAppData: { |
| 9 | + tabsCount?: { |
| 10 | + count?: number; |
| 11 | + } |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +// Load the hook module asynchronously |
| 16 | +function useDynamicHookShim() { |
| 17 | + const [hook, setHook] = React.useState<(() => HooKType) | null>(null); |
| 18 | + |
| 19 | + React.useEffect(() => { |
| 20 | + let cancelled = false; |
| 21 | + |
| 22 | + async function load() { |
| 23 | + try { |
| 24 | + const module = await import("@edx/frontend-plugin-notifications"); |
| 25 | + const hookFn = module.useAppNotifications ?? module.default; |
| 26 | + if (!cancelled) { |
| 27 | + // `module.useAppNotifications` is itself a hook |
| 28 | + setHook(() => hookFn); |
| 29 | + } |
| 30 | + } catch (err: any) { |
| 31 | + // If the module cannot be found, just keep `hook` as null. |
| 32 | + console.error("Failed to load notifications plugin:", err); |
| 33 | + // No hook – the UI will fall back to the placeholder. |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + load(); |
| 38 | + |
| 39 | + return () => { |
| 40 | + cancelled = true; |
| 41 | + }; |
| 42 | + }, []); |
| 43 | + |
| 44 | + return hook; |
| 45 | +} |
| 46 | + |
| 47 | +// Component that actually calls the loaded hook |
| 48 | +function NotificationHookConsumer({ hook }: { hook: () => HooKType }) { |
| 49 | + // The hook is now called on **every** render of this component |
| 50 | + const { notificationAppData } = hook(); |
| 51 | + |
| 52 | + if (!notificationAppData?.tabsCount?.count || notificationAppData?.tabsCount?.count < 1) { |
| 53 | + return null; |
| 54 | + } |
| 55 | + |
| 56 | + // You can use `hookResult` here as needed |
| 57 | + return ( |
| 58 | + <small className="d-flex"> |
| 59 | + <Icon className="mr-1" size="md" src={NotificationsNone} /> |
| 60 | + <FormattedMessage |
| 61 | + {...messages.notificationMetadataTitle} |
| 62 | + values={{ count: notificationAppData?.tabsCount?.count }} |
| 63 | + /> |
| 64 | + </small> |
| 65 | + ); |
| 66 | +} |
| 67 | + |
| 68 | +// Main component |
| 69 | +export const NotificationStatusIcon = () => { |
| 70 | + const loadedHook = useDynamicHookShim(); |
| 71 | + |
| 72 | + if (!loadedHook) { |
| 73 | + return null; |
| 74 | + } |
| 75 | + |
| 76 | + // Once loaded, delegate to a component that calls the hook |
| 77 | + return <NotificationHookConsumer hook={loadedHook} />; |
| 78 | +}; |
| 79 | + |
0 commit comments