I am creating a language switcher for my application. So far, I can support 4 languages (English [en], Spanish [sp], French [fr], and Arabic [ar]). I have already converted all of the language properties files to JSON and I can import those files into my .jsx file. However, when it comes to setting the language, I am running into issues.
For Example:
I have this line of code: <h1>{messages.en["user.userprofile"]}</h1>
This translates to User Profile in English. If I switch the language to French <h1>{messages.fr["user.userprofile"]}</h1>
, I will get: Profil d'utilisateur.
Instead of hardcoding the language, I am trying to get it to change dynamically. I am using Redux to load the user profile.
const defaultLanguage = useSelector(
(state) => state.profileReducer.profile.language || []
);
...
<h1>{messages[defaultLanguage]["user.userprofile"]}</h1>
I want to get the defaultLanguage
on page load. For instance, if the user's language is English, defaultLanguage
will be set to en
. However when I do this, I get a white screen and this error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'user.userprofile')
at UserProfileNew (UserProfileNew.jsx?e01f:146)
at renderWithHooks (react-dom.development.js?61bb:14985)
at mountIndeterminateComponent (react-dom.development.js?61bb:17811)
at beginWork (react-dom.development.js?61bb:19049)
at HTMLUnknownElement.callCallback (react-dom.development.js?61bb:3945)
at Object.invokeGuardedCallbackDev (react-dom.development.js?61bb:3994)
at invokeGuardedCallback (react-dom.development.js?61bb:4056)
at beginWork$1 (react-dom.development.js?61bb:23964)
at performUnitOfWork (react-dom.development.js?61bb:22776)
at workLoopSync (react-dom.development.js?61bb:22707)
However, if I comment the h1
tag out and and put console.log
for defaultLanguage
, I notice that it prints 5 times. On the first 2 times, defaultLanguage
is set to []
. Then on the last 3 times, defaultLangauge
is set to the user's language value loaded from Redux. How can I get this initialized on page load so that it won't be undefined? Am I missing something or do I need to change how I write defaultLanguage
in the h1
tag?
CodePudding user response:
Actually your problem is not in Redux.
When you are trying to get value from messages.en["user.userprofile"]
you suppose that you getting value from messages.en.user.userprofile
but no, it doesn't work this way - JS considers it as getting value from an object by key user.userprofile
and object structure for JS is
{
'messages': {
'en': {
'user.userprofile': {
}
}
}
}
The most simple an cheapest solution for you problem is using method get
from lodash, or any other similar utility library. Thus you'll be able to write
get(messages.en, 'user.userprofile', [])
and be sure to get values by composed key.