store locale into localstorage

This commit is contained in:
Aarni Halinen
2021-04-04 22:59:09 +03:00
parent f8f433463f
commit ea20fdbecf
+24 -6
View File
@@ -4,6 +4,9 @@ import React, {
import fi from "./locales/fi/common.json";
import en from "./locales/en/common.json";
type Lang = "fi" | "en";
const LOCAL_STORAGE_KEY = "locale";
type TranslateFunc = (key: string) => string;
const translateEn: TranslateFunc = (key) => {
@@ -24,16 +27,24 @@ const translateFi: TranslateFunc = (key) => {
};
interface Store {
language: string;
changeLanguage: React.Dispatch<string>,
language: Lang;
changeLanguage: React.Dispatch<Lang>,
}
let initialLanguage: Lang = "fi";
try {
const storedLang = localStorage.getItem(LOCAL_STORAGE_KEY) as Lang;
initialLanguage = storedLang;
} catch (err) {
// Just ignore if fails to get value from browser (server etc.)
}
const initialState: Store = {
language: "fi",
language: initialLanguage,
changeLanguage: null,
};
const Reducer = (state: Store, action: string) => {
const Reducer = (state: Store, action: Lang) => {
switch (action) {
case "fi":
return {
@@ -53,8 +64,15 @@ const Reducer = (state: Store, action: string) => {
const LocaleContext = createContext(initialState);
const LocaleStore: React.FC = ({ children }) => {
const [state, changeLanguage] = useReducer(Reducer, initialState);
const [state, dispatch] = useReducer(Reducer, initialState);
const changeLanguage = (action: Lang) => {
dispatch(action);
try {
localStorage.setItem(LOCAL_STORAGE_KEY, action);
} catch (err) {
// Just ignore if fails to store value in user's browser
}
};
return (
<LocaleContext.Provider value={{ ...state, changeLanguage }}>
{children}