Search code examples
react-nativereact-reduxreact-i18next

How to use translation i18n in React without hook?


I need to do translation in my middleware (import { Middleware } from 'redux') logic, but I can't use useTranslation hook (import { useTranslation } from 'react-i18next'). How do you standardly solve such situation?

Error message:

React Hook "useTranslation" is called in function "myFunction: Middleware<{}, RootStateType>" which is neither a React function component or a custom React Hook function.

my code(shortened):

import PushNotificationIOS from '@react-native-community/push-notification-ios';
import { Middleware } from 'redux';
import { getType } from 'typesafe-actions';

const scheduleNotificationSettings = (notification: NotificationT): void => {
 PushNotificationIOS.scheduleLocalNotification({
        fireDate: notification.startDate,
        alertTitle: TRANSLATE_SOMEHOW(notification.titleKey),<--- ! HERE ! ¯\_( ❛ ͜ʖ ︡❛)_/¯
        alertBody: TRANSLATE_SOMEHOW(notification.bodyKey),  <--- ! HERE !
        alertAction: 'view',
        isSilent: false,
        repeatInterval: 'week',
      });
};

export const handleAction: Middleware<{}, RootStateType> = () => {
  return next => {
    return action => {
      const result = next(action);
      switch (action.type) {
        case getType(create): {
          createNotification(action.payload);
          break;
        }
        case getType(delete): {
          removeNotification(action.payload);
          break;
        }
        default:
          return result;
      }
      return result; //pass events to other middleware
    };
  };

Solution

  • I hope I understand your problem correctly, but I assume you have initialized i18n already, so outside of react components don't use the hook just import it like this:

    import i18n from 'i18next';
    

    then use it:

    i18n.t(youri18nKey);