hozana / next-translate-routes

Flexible and translated routes for Next.js without custom server
MIT License
115 stars 30 forks source link

translate-routes and language change #44

Closed dsm-ostec closed 2 years ago

dsm-ostec commented 2 years ago

Hey there,

I'm using next-translate-routes and it works fine so far. But when I change the language, the paths were not redirected, but the site-content is correct. My code for languageChange is like this:

function changeLanguage(language) {
    i18n
      .changeLanguage(language === 'EN' ? 'en' : 'de')
      .then((t) => {
        t('key');
      })
      .catch((err) => {
        console.log('something went wrong loading', err);
      });
    router.push({ pathname, query }, asPath, { locale: language });
  }

my i18 config:

i18n: {
    defaultLocale: 'en',
    locales: ['en', 'de'],
  },

and my _routes.json:

{
  "contact": {
    "en": "contact",
    "de": "kontakt"
  }
}

eg.: I am on page /de/kontakt and use the languageSwitcher. The url changed to /kontakt. The component "contact" is correctly loaded and its translated content too. But the url is false. If I refresh the page in browser, the re-direrection to/contact is done correctly.

How can I change my changeLanguage-Function to make this work?

cvolant commented 2 years ago

:thinking: Strange... router.push({ pathname, query }, asPath, { locale: 'en' }) should redirect to /contact... Could you try using next-translate-routes@1.9.0-2? If if it does not work, could you post a reproduction that I can investigate?

dsm-ostec commented 2 years ago

Sorry. I forget to mention I use next-translate-routes@1.8.0-1 because of this issue: https://github.com/hozana/next-translate-routes/issues/42. All later versions cause the "no translate routes"-problem.

Maybe it's important to say, thatr I use also next-i18next package to translate my content.

If I change my changeLanguage like this, the url is correct after reload (but of course I know its not a nice solution :) )

router.push({ pathname, query }, asPath, { locale: language }).then(() => {
      window.location.reload();
    });

I'll try to set up a sandbox-environment to reproduce the issue.

dsm-ostec commented 2 years ago

Hello again. Have a look at this sandbox-code: Sandbox Language change translated routes. If you are on page /news (englisch) an click to button "change to fr" url changes to "fr/news" instead of "fr/actualite" but the content of the page is rendered correct. After reload the url is correct.

EN: image

After klick on button: image

After reload: image

cvolant commented 2 years ago

! I finally got it. It took me a while but here is the problem: you set the as prop to asPath in router.push. next-translate-routes lets you use a custom as prop if you want to: it means "I want to go there but then here is the url I want to display".