Fixed Version (HMR-safe). Avoids HMR issues from unstable inline defaults.

This commit is contained in:
Tola Leng
2025-05-24 04:45:47 +08:00
parent c8323e91b0
commit df047541b9
+13 -13
View File
@@ -1,4 +1,3 @@
import React, { createContext, useContext, useState, ReactNode } from "react"; import React, { createContext, useContext, useState, ReactNode } from "react";
import { translations, Language, TranslationModule, TranslationKey } from "@/translations"; import { translations, Language, TranslationModule, TranslationKey } from "@/translations";
@@ -8,34 +7,35 @@ type LanguageContextType = {
t: <M extends TranslationModule>(key: string, module?: M) => string; t: <M extends TranslationModule>(key: string, module?: M) => string;
}; };
const LanguageContext = createContext<LanguageContextType>({ // ❗ Create the context with `undefined` to enforce provider usage
language: "en", const LanguageContext = createContext<LanguageContextType | undefined>(undefined);
setLanguage: () => {},
t: () => "",
});
export const useLanguage = () => useContext(LanguageContext); // ✅ Stable custom hook
export const useLanguage = () => {
const context = useContext(LanguageContext);
if (!context) {
throw new Error("useLanguage must be used within a LanguageProvider");
}
return context;
};
export const LanguageProvider = ({ children }: { children: ReactNode }) => { export const LanguageProvider = ({ children }: { children: ReactNode }) => {
const [language, setLanguage] = useState<Language>("en"); const [language, setLanguage] = useState<Language>("en");
const t = <M extends TranslationModule>(key: string, module?: M): string => { const t = <M extends TranslationModule>(key: string, module?: M): string => {
// If module is provided, look up in that specific module
if (module) { if (module) {
const translatedValue = translations[language][module][key as TranslationKey<M>]; const translatedValue = translations[language][module][key as TranslationKey<M>];
return typeof translatedValue === 'string' ? translatedValue : key; return typeof translatedValue === "string" ? translatedValue : key;
} }
// If no module is provided, search through all modules
for (const mod in translations[language]) { for (const mod in translations[language]) {
const moduleKey = mod as TranslationModule; const moduleKey = mod as TranslationModule;
const translatedValue = translations[language][moduleKey][key as any]; const translatedValue = translations[language][moduleKey][key as any];
if (translatedValue && typeof translatedValue === 'string') { if (translatedValue && typeof translatedValue === "string") {
return translatedValue; return translatedValue;
} }
} }
// If no translation found, return the key
return key; return key;
}; };
@@ -44,4 +44,4 @@ export const LanguageProvider = ({ children }: { children: ReactNode }) => {
{children} {children}
</LanguageContext.Provider> </LanguageContext.Provider>
); );
}; };