|
1 | 1 | import clsx from 'clsx' |
| 2 | +import {PrivateMessageChannel} from 'common/supabase/private-messages' |
2 | 3 | import {PrivateUser} from 'common/user' |
3 | 4 | import {getNotificationDestinationsForUser} from 'common/user-notification-preferences' |
4 | 5 | import {usePathname} from 'next/navigation' |
| 6 | +import {createContext, ReactNode, useContext} from 'react' |
5 | 7 | import {BiEnvelope, BiSolidEnvelope} from 'react-icons/bi' |
6 | 8 | import {Row} from 'web/components/layout/row' |
7 | 9 | import {useUnseenPrivateMessageChannels} from 'web/hooks/use-private-messages' |
8 | 10 | import {usePrivateUser} from 'web/hooks/use-user' |
9 | 11 |
|
| 12 | +// Shared unseen-channels state so the desktop sidebar icon and the mobile |
| 13 | +// bottom-nav icon (both mounted at once) consume a single fetch instead of each |
| 14 | +// running their own `useUnseenPrivateMessageChannels`. |
| 15 | +const UnseenMessageChannelsContext = createContext<PrivateMessageChannel[]>([]) |
| 16 | + |
| 17 | +export function UnseenMessageChannelsProvider(props: {children: ReactNode}) { |
| 18 | + const {children} = props |
| 19 | + const privateUser = usePrivateUser() |
| 20 | + // The hook is always called (no conditional hooks); `enabled` gates the fetch |
| 21 | + // so signed-out users don't hit the authed endpoint. |
| 22 | + const {unseenChannels} = useUnseenPrivateMessageChannels(false, !!privateUser) |
| 23 | + return ( |
| 24 | + <UnseenMessageChannelsContext.Provider value={unseenChannels}> |
| 25 | + {children} |
| 26 | + </UnseenMessageChannelsContext.Provider> |
| 27 | + ) |
| 28 | +} |
| 29 | + |
10 | 30 | export function UnseenMessagesBubble(props: {className?: string}) { |
11 | 31 | const {className} = props |
12 | 32 | const privateUser = usePrivateUser() |
@@ -50,7 +70,7 @@ function InternalUnseenMessagesBubble(props: { |
50 | 70 | }) { |
51 | 71 | const {privateUser, className, bubbleClassName} = props |
52 | 72 |
|
53 | | - const {unseenChannels} = useUnseenPrivateMessageChannels(false) |
| 73 | + const unseenChannels = useContext(UnseenMessageChannelsContext) |
54 | 74 | const pathName = usePathname() |
55 | 75 |
|
56 | 76 | const {sendToBrowser} = getNotificationDestinationsForUser(privateUser, 'new_message') |
|
0 commit comments