Redirecting to dynamic translated path not working as expected when changing language
See original GitHub issueDescribe the bug
I created a language switcher component to use different languages, which can be accessed globally inside my app. Also there are different dynamic paths in my application that can change according to the selected language. E.g. the FAQ page can be accessed with /help-contact/faq
(english version) and /hilfe-kontakt/faq
(german version).
If the language is now getting changed on a dynamic page like the FAQ page, the new dynamic path should be read from the translation files and the new url should be pushed accordingly:
import { useTranslation } from "next-i18next";
import { useRouter } from 'next/router';
const CountrySwitch = () => {
const { t } = useTranslation();
const router = useRouter();
const onSelect = () => {
const pathname = router.pathname;
const asPath = t('faqPath', { lng: selectedLocale });
router.push(
{
pathname,
},
asPath,
{ locale: selectedLocale }
);
}
return (
<div>
<Button
key="submit"
onClick={onSelect}
>
Select new language
</Button>
</div>
)
}
Unfortunately t('faqPath', { lng: selectedLocale })
is still getting the old language path string instead of the new one. But when ommiting the router.push()
statement at the end of the function everything works as expected and the correct translation is being returned.
IMPORTANT: This bug only happens when changing the language from the default one to any other language. When changing it back to the default language, everything works as expected again.
Is there any known error when using the useTranslation
hook from next-i18next
module to have dynamic language paths combined with the useRouter
from next?
Occurs in next-i18next version
^11.0.0
Steps to reproduce
See code above
Expected behaviour
When changing the language the new path translation should be retrieved according to the selected language and then pushed.
OS (please complete the following information)
- Device: MBP 2018 16"
- Browser: Chrome 101.0.4951.64
Issue Analytics
- State:
- Created a year ago
- Comments:7 (4 by maintainers)
That is not a minimal reproduction.
That’s because your
de/common.json
file is empty.Please seek help on StackOverflow.
That is most likely because the data for
selectedLocale
is not actually loaded, because it is different than the current locale.next-i18next
only sends the current locale and current namespaces down to the client. If we sent all namespaces or all locales, there wouldn’t be much point in an i18n package.I would suggest keeping your localised route data in a simple JavaScript object, but if you really want to treat it as localised content, you will need to call
i18n.addResource
, or perhapsaddResourceBundle
, before you try to translate into a locale besides the current one.