From ea20fdbecf783f01434ce8510bfbe293f23e961e Mon Sep 17 00:00:00 2001 From: Aarni Halinen Date: Sun, 4 Apr 2021 22:59:09 +0300 Subject: [PATCH] store locale into localstorage --- src/i18n/index.tsx | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/src/i18n/index.tsx b/src/i18n/index.tsx index a0c1506..184a565 100644 --- a/src/i18n/index.tsx +++ b/src/i18n/index.tsx @@ -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, + language: Lang; + changeLanguage: React.Dispatch, +} + +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 ( {children}