I have a select with 2 options (en, no), which switches the language onChange.
I store selected language to localStorage
. Because I'm using Remix I cannot simply access localStorage, because of the server-side rendering, so I'm using:
if (typeof window !== 'undefined') {
const localLanguage = localStorage.getItem('language');
}
Select component:
<select
name="language"
id="language-select"
defaultValue={language}
onChange={e => changeLanguageHandler(e.target.value)}
>
<option value="no" label="NO">
Norwegian
</option>
<option value="en" label="EN">
English
</option>
</select>
Translation function:
export function useLocalTranslation() {
const [language, setLanguage] = React.useState(() => {
// react lazy initial state
// ( i think i should be using lazy initial state, because of the serverside rendering
if (typeof window !== 'undefined') {
const initialState = localStorage.getItem('language') ?? 'no';
return initialState;
}
});
const no = useNoTranslations();
React.useEffect(() => {
const savedLanguage = localStorage.getItem('language');
if (savedLanguage) {
setLanguage(savedLanguage);
}
}, []);
const t = React.useCallback(
(key: TKey) => {
if (key === '0') return '0';
if (typeof window !== 'undefined') {
const currentLanguage = localStorage.getItem('language');
if (currentLanguage === 'no') {
// console.log(currentLanguage);
return no?.[key as string] ?? en[key as TranslationsKeys] ?? key;
}
// console.log(currentLanguage);
}
return en[key as TranslationsKeys] ?? key;
},
[no],
);
function changeLanguageHandler(lang: string) {
setLanguage(lang);
localStorage.setItem('language', lang);
}
return { t, language, changeLanguageHandler };
}
My goal is to have selected option saved and persistent on page refresh, now when I refresh the page, it gets reseted to NO (Norwegian)
CodePudding user response:
I guess you can solve this by giving value attribute instead of defaultValue.