React on('languageChanged', isn't working for detecting language change

659 views Asked by At

I'm quite new to react and I'm searching the best way to detect when user change language. I'm using next translate to translate resources but for some ressource I'm getting from API, I need to change them manually. Here is the way I'm using default ressources:

On page:

const { t } = useTranslation("member");

That calls:

import { I18n } from '.';
export default function useTranslation(defaultNS?: string): I18n;

And here is the way language is changed into the picker component:

router.replace(router.asPath, undefined, { locale: locale/*, shallow: true*/ });

Here are things I've tried so far: I'm not into a component (it's a jsx page) so I think I cannot use

componentDidUpdate(prevProps, prevState) { if (this.props.t !== prevProps.t) { console.log(this.props.i18n.language); } }

It gives me a TypeError: Cannot read property 'props' of undefined

I've tried that too but it

import I18n from 'i18n';
i18next.on('languageChanged', function(lng) {})

Gives me TypeError: _next_translate_root_i18n__WEBPACK_IMPORTED_MODULE_0___default(...).on is not a function

1

There are 1 answers

1
oluroyleseyler On BEST ANSWER
import { useEffect } from "react";
import { useRouter } from "next/router";
import { useTranslation } from "next-translate";

function MyPage() {
  const router = useRouter();
  const { t, i18n } = useTranslation();

  useEffect(() => {
    console.log(`Language changed to ${i18n.language}`);
    // Do something here when the language changes
  }, [i18n.language]);

  return <div>{t("hello")}</div>;
}

export default MyPage;

using the useEffect hook to listen for changes to the i18n.language property, which is automatically updated by next-translate when the user changes the language. When the language changes, the effect function is called and you can do something in response.

Note that you should include i18n.language in the dependency array of useEffect. This ensures that the effect function is called every time the language changes.