Created
June 9, 2022 10:37
-
-
Save eduardoacskimlinks/99e7d500291c2242a8a1d1a52c9ce8b2 to your computer and use it in GitHub Desktop.
useInternationalization - hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Custom Hook -> useInternationalization() | |
import i18n from "i18next" | |
import { useState, useEffect } from "react" | |
import { initReactI18next } from "react-i18next" | |
const NOTFETCHED = "notFetched" | |
const FETCHING = "fetching" | |
const FETCHED = "fetched" | |
const ERROR = "error" | |
export const useInternationalization = () => { | |
// Status of the request can be: notFetched, fetching, fetched, error | |
const [status, setStatus] = useState(NOTFETCHED) | |
const [serverError, setServerError] = useState(null) | |
useEffect(() => { | |
setStatus(FETCHING) | |
const fetchData = async () => { | |
try { | |
await chrome.runtime.sendMessage({ type: "internationalization" }, (response) => { | |
setStatus(FETCHED) | |
i18n.use(initReactI18next) // pass the i18n instance to react-i18next. | |
.init({ | |
debug: true, | |
fallbackLng: "en", | |
react: { | |
useSuspense: false, | |
}, | |
interpolation: { | |
// not needed for react as it escapes by default | |
escapeValue: false, | |
}, | |
resources: { | |
en: response, | |
}, | |
}) | |
}) | |
} catch (error) { | |
setServerError(error) | |
setStatus(ERROR) | |
} | |
} | |
if (status !== FETCHED && status !== FETCHING) { | |
fetchData() | |
} | |
}, [status]) | |
return { status, serverError } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment