Created
May 15, 2022 01:28
-
-
Save gregfenton/0272d1dec3ffcca1507280da7ec212b4 to your computer and use it in GitHub Desktop.
An example Context API provider for use with the i18next-node-firestore-backend
This file contains hidden or 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
import React, {createContext, useEffect, useState} from "react"; | |
import i18next from "i18next"; | |
import {initReactI18next} from "react-i18next"; | |
import Backend from "i18next-node-firestore-backend"; | |
import {FIRESTORE} from "../myFirebase"; | |
// export const I18NEXT_FS_BKEND_LANGUAGE_LIST_FIELD_NAME = 'languages'; | |
const I18NEXT_DEFAULT_NAMESPACE = "core"; | |
const I18NEXT_FS_BKEND_COLLECTION_NAME = "config/type/i18n"; | |
const I18NEXT_FS_BKEND_DATA_FIELD_NAME = "data"; | |
const I18NEXT_FS_BKEND_LANGUAGE_FIELD_NAME = "language"; | |
const I18NEXT_FS_BKEND_NAMESPACE_FIELD_NAME = "namespace"; | |
export const I18NContext = createContext({}); | |
const I18NProvider = (props) => { | |
const {isUserLoggedIntoFirebaseAuth, children} = props; | |
const [i18nInitialized, setI18nInitialized] = useState(false); | |
useEffect(() => { | |
const setupI18Next = async () => { | |
await i18next | |
.use(Backend) | |
.use(initReactI18next) | |
.init({ | |
backend: { | |
firestore: FIRESTORE, | |
collectionName: I18NEXT_FS_BKEND_COLLECTION_NAME, | |
languageFieldName: I18NEXT_FS_BKEND_LANGUAGE_FIELD_NAME, | |
namespaceFieldName: I18NEXT_FS_BKEND_NAMESPACE_FIELD_NAME, | |
dataFieldName: I18NEXT_FS_BKEND_DATA_FIELD_NAME, | |
debug: false, | |
}, | |
debug: false, | |
defaultNS: I18NEXT_DEFAULT_NAMESPACE, | |
fallbackLng: "en-CA", | |
interpolation: { | |
escapeValue: false, // not needed for react | |
}, | |
load: "currentOnly", | |
ns: I18NEXT_DEFAULT_NAMESPACE, | |
react: { | |
useSuspense: false, // <---- this will do the magic | |
}, | |
}); | |
}; | |
if (isUserLoggedIntoFirebaseAuth) { | |
setupI18Next(); | |
setI18nInitialized(true); | |
} | |
}, [isUserLoggedIntoFirebaseAuth]); | |
return ( | |
<I18NContext.Provider value={{}}> | |
{isUserLoggedIntoFirebaseAuth && i18nInitialized ? children : "Loading i18Next..." } | |
</I18NContext.Provider> | |
); | |
}; | |
export default I18NProvider; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment