Fixed Version (HMR-safe). Avoids HMR issues from unstable inline defaults.
This commit is contained in:
@@ -1,4 +1,3 @@
|
||||
|
||||
import React, { createContext, useContext, useState, ReactNode } from "react";
|
||||
import { translations, Language, TranslationModule, TranslationKey } from "@/translations";
|
||||
|
||||
@@ -8,34 +7,35 @@ type LanguageContextType = {
|
||||
t: <M extends TranslationModule>(key: string, module?: M) => string;
|
||||
};
|
||||
|
||||
const LanguageContext = createContext<LanguageContextType>({
|
||||
language: "en",
|
||||
setLanguage: () => {},
|
||||
t: () => "",
|
||||
});
|
||||
// ❗ Create the context with `undefined` to enforce provider usage
|
||||
const LanguageContext = createContext<LanguageContextType | undefined>(undefined);
|
||||
|
||||
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 }) => {
|
||||
const [language, setLanguage] = useState<Language>("en");
|
||||
|
||||
const t = <M extends TranslationModule>(key: string, module?: M): string => {
|
||||
// If module is provided, look up in that specific module
|
||||
if (module) {
|
||||
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]) {
|
||||
const moduleKey = mod as TranslationModule;
|
||||
const translatedValue = translations[language][moduleKey][key as any];
|
||||
if (translatedValue && typeof translatedValue === 'string') {
|
||||
if (translatedValue && typeof translatedValue === "string") {
|
||||
return translatedValue;
|
||||
}
|
||||
}
|
||||
|
||||
// If no translation found, return the key
|
||||
return key;
|
||||
};
|
||||
|
||||
@@ -44,4 +44,4 @@ export const LanguageProvider = ({ children }: { children: ReactNode }) => {
|
||||
{children}
|
||||
</LanguageContext.Provider>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user