Is it possible to use i18n localization for redux Actions?
Asked Answered
P

2

6

I was trying to implement i18n localization for Redux Action functions, but i constantly recieve different hook errors. When i implemented i18n this way i recieve error.

Line 428:17: React Hook "useTranslation" is called in function "sendDataRequest" that is neither a React function component nor a custom React Hook function.

import { useTranslation } from "react-i18next";

export const sendDataRequest = (requestId) => {
  const { t } = useTranslation();
  return async (dispatch) => {
    try {
      dispatch(sendDataRequest());
      await dataAPI.sendDataRequest({ requestId });
      notification.success({
        message: t('infoPage.requestSentSuccessfully'),      
     });
      dispatch(sendDataSuccess());
    } catch (error) {
      dispatch(sendDataFailure());
      console.error(error);
    }
  }
}

Then i moved const { t } = useTranslation(); inside of return statement. But then i recieved another error enter image description here It looks like I obviously using it wrong here. But i cannot find any examples on i18n being used in Actions. Does anyone knows is it even possible to use i18b in Actions?

Pascasia answered 4/11, 2021 at 12:0 Comment(1)
You must use react hooks inside react function component. This is the rule. You need to refactor your code. Why not create a custom hook which uses useTranslation hook internally and calls the notification.success() method after the data request finished?Cambell
L
5

Check out https://github.com/i18next/react-i18next/issues/909

You need to gain access to your i18next instance. The one you create somewhere in your codebase. With this instance you can simply call i18n.t("my.translation.key") to translate. This is completely independent from react.

Ledford answered 5/11, 2021 at 14:39 Comment(0)
C
1

Yes, it's possible.

  1. You need to import your i18n instance in your actions/reducer:

    import i18n from '../i18n_init_file';

  2. After that you could use the instance inside your actions like that:

    i18n.t('STRING_TO_TRANSLATE');

    or

    i18n.changeLanguage('NEW_LOCALE').then();

Carnay answered 28/2, 2023 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.