|
72 | 72 | * shape: ten literal loaders, no static catalogue import, no key in both |
73 | 73 | * places. |
74 | 74 | */ |
75 | | -import { useCallback, useEffect, useSyncExternalStore } from 'react'; |
| 75 | +import { useCallback, useContext, useEffect, useSyncExternalStore } from 'react'; |
76 | 76 | import type { i18n as I18nInstance } from 'i18next'; |
| 77 | +import { I18nContext, getI18n } from 'react-i18next'; |
77 | 78 | import { DEFAULT_BUILT_IN_LANGUAGE, getLoadedBuiltInLocales, matchLanguageTag } from '../../locales/registry.js'; |
78 | | -import { useObjectTranslation } from '../../provider.js'; |
79 | 79 |
|
80 | 80 | /** One language's catalogue: a partial pack holding the `marketplace` group. */ |
81 | 81 | export type MarketplaceCatalogue = Readonly<Record<string, unknown>>; |
@@ -294,12 +294,27 @@ const readVersion = (): number => version; |
294 | 294 | * anyway, so it answers `ready`. |
295 | 295 | */ |
296 | 296 | export function useMarketplaceNamespace(): MarketplaceNamespaceState { |
297 | | - const { i18n } = useObjectTranslation(); |
| 297 | + // The instance react-i18next hands `t()`: the provider's, else the one |
| 298 | + // `initReactI18next` installed. Read directly rather than through |
| 299 | + // `useTranslation`, which warns (NO_I18NEXT_INSTANCE) where there is none — |
| 300 | + // a host or a test that renders a marketplace component bare. |
| 301 | + const instance = (useContext(I18nContext)?.i18n ?? getI18n()) as I18nInstance | undefined; |
298 | 302 | // Re-render when a catalogue lands or fails — the store write this hook |
299 | 303 | // makes is silent, so react-i18next's own subscription never hears of it. |
300 | 304 | useSyncExternalStore(subscribe, readVersion, readVersion); |
301 | | - const instance = i18n as I18nInstance | undefined; |
302 | | - const lang = instance?.language || DEFAULT_BUILT_IN_LANGUAGE; |
| 305 | + // …and when the instance switches language. |
| 306 | + const subscribeLanguage = useCallback( |
| 307 | + (listener: () => void) => { |
| 308 | + if (typeof instance?.on !== 'function') return () => undefined; |
| 309 | + instance.on('languageChanged', listener); |
| 310 | + return () => { |
| 311 | + instance.off('languageChanged', listener); |
| 312 | + }; |
| 313 | + }, |
| 314 | + [instance], |
| 315 | + ); |
| 316 | + const readLanguage = (): string => instance?.language || DEFAULT_BUILT_IN_LANGUAGE; |
| 317 | + const lang = useSyncExternalStore(subscribeLanguage, readLanguage, readLanguage); |
303 | 318 |
|
304 | 319 | const retry = useCallback(() => { |
305 | 320 | let started = false; |
|
0 commit comments