Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save eduardoacskimlinks/99e7d500291c2242a8a1d1a52c9ce8b2 to your computer and use it in GitHub Desktop.
Save eduardoacskimlinks/99e7d500291c2242a8a1d1a52c9ce8b2 to your computer and use it in GitHub Desktop.
useInternationalization - hook
// 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