Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

function t() { [native code] } #1675

Open
cosoc opened this issue Sep 10, 2023 · 14 comments
Open

function t() { [native code] } #1675

cosoc opened this issue Sep 10, 2023 · 14 comments

Comments

@cosoc
Copy link

cosoc commented Sep 10, 2023

🐛 Bug Report

Display abnormalities may occur when loading the cut flower page for the first time or refreshing it multiple times.

console pringt Warning:

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

UI Display Error
image

code

I18NExtManage.tsx

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { resources } from './I18NResources';


i18n
	.use(initReactI18next)
	.init({
		resources,
		fallbackLng: ["en_US","zh_CN","en_GB"],
		ns: ['global', 'dynamics',],
		defaultNS: 'global',
		lng: "en_US",
		debug: false,
		returnNull: false,
		returnEmptyString: true,
		interpolation: {
			escapeValue: false,
		},
		react:{
			bindI18n:'added removed languageChanged loaded',
			bindI18nStore: 'added removed languageChanged loaded',
			nsMode: 'default'
		}
	});
export default i18n;

I18NResources.ts

import { zhCNGlobal } from '../lang/zh_CN/global'
import { enUSGlobal } from '../lang/en_US/global'
import i18n from './I18NExtManage';

export const resources = {
	"en_US": {
		global: enUSGlobal
	},
	"zh_CN": {
		global: zhCNGlobal
	}
}

export const setResources = (resources:any) =>  {
	for (let key in resources) {				
		i18n.addResources(key,"dynamics",resources[key]);
	}
}

Call functions

  ...
    return (
        <div>
            {t('global:MY.KEY')?.toString() }
        </div>
            
    );
  

Error if not adding toString function

Occasionally report an error

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.

I ensure that the returned value must be a string

export const setResources = (resources:any) =>  {
	for (let key in resources) {				
		i18n.addResources(key,"dynamics",resources[key]);
	}
}

I guess the exception is caused when the page calls the following function, but the added event has been added and re-rendered, but it still doesn't work.

Expected behavior

Regardless of the first load or page switching, refreshing, resource addition, the page displays normally

Environment

runtime version*: i.e. node v18.17.1

  • i18next version: 23.5.1
  • os: Debian12
@adrai
Copy link
Member

adrai commented Sep 10, 2023

please provide a minimal reproducible example repository or codesandbox...
I suspect, this happens, bacause you're lazy loading with addResources, and the you may call the t function with a key that is not yet loaded

@cosoc
Copy link
Author

cosoc commented Sep 10, 2023

please provide a minimal reproducible example repository or codesandbox... I suspect, this happens, bacause you're lazy loading with addResources, and the you may call the t function with a key that is not yet loaded

I modified the logic cut-in timing of dynamically adding resources, and it has returned to normal.

@cosoc cosoc closed this as completed Sep 10, 2023
@cosoc cosoc reopened this Sep 11, 2023
@cosoc
Copy link
Author

cosoc commented Sep 11, 2023

There is still a problem, your words reminded me that I did use lazy loading for routing. Remember, after using it, my i18n is not working properly! I organized a small demo but couldn't reproduce my anomalies.

@cosoc
Copy link
Author

cosoc commented Sep 18, 2023

If there is no initialization, why is partial translation possible!
image
Clicking on this component can control the display and hiding of another display component. When repeatedly clicked, organizational requests will appear, and then clicking again will restore normal operation

@cosoc
Copy link
Author

cosoc commented Sep 20, 2023

I was sure it was an encapsulation problem with react-i18nex. When I directly removed react-i18nex and used the original i18nex library to implement the page re-rendering logic, all the problems were solved.

When a component is repeatedly added and deleted, react-i18next will have the above problems. It may be that the library performs repeated rendering, or it may be caused by some problem. The problem is currently unknown.

@jamesrwaugh
Copy link

Screenshot from 2023-09-25 21-25-30

I'm also running into this. I am not explicitly calling addResources anywhere in the app .
How can I make sure everything is first loaded, as @adrai suggests?
I am using a custom driver with Tauri, that uses built-in functionality there to load the translations.

export const TauriBackend: BackendModule = {
  type: "backend",
  init: function (
    services: Services,
    backendOptions: object,
    i18nextOptions: InitOptions<object>
  ): void {
    // Nothing to do
  },
  read: function (
    language: string,
    namespace: string,
    callback: ReadCallback
  ): void {
    console.log("i18n", language, namespace);
    invoke<string>("read_translations", {
      language: language,
      namespace: namespace,
    })
      .then((fileContent) => {
        const data = JSON.parse(fileContent);
        callback(null, data);
      })
      .catch((ex) => callback(ex, null));
  },
};

@adrai
Copy link
Member

adrai commented Sep 26, 2023

use Suspense or check the ready flag: https://react.i18next.com/latest/usetranslation-hook#not-using-suspense

@cosoc
Copy link
Author

cosoc commented Sep 26, 2023

使用 Suspense 或检查就绪标志:https://react.i18next.com/latest/usetranslation-hook#not-using-suspense

ready para I tried, but it was still a mistake

@cosoc
Copy link
Author

cosoc commented Sep 26, 2023

截图自 2023-09-25 21-25-30

我也遇到了这个问题。我没有明确调用addResources应用程序中的任何位置。 我如何确保首先加载所有内容,如@adrai建议? 我正在使用 Tauri 的自定义驱动程序,它使用内置功能来加载翻译。

export const TauriBackend: BackendModule = {
  type: "backend",
  init: function (
    services: Services,
    backendOptions: object,
    i18nextOptions: InitOptions<object>
  ): void {
    // Nothing to do
  },
  read: function (
    language: string,
    namespace: string,
    callback: ReadCallback
  ): void {
    console.log("i18n", language, namespace);
    invoke<string>("read_translations", {
      language: language,
      namespace: namespace,
    })
      .then((fileContent) => {
        const data = JSON.parse(fileContent);
        callback(null, data);
      })
      .catch((ex) => callback(ex, null));
  },
};

I also encountered a problem with the tauri program. Currently, I am using the native i18next to temporarily solve the problem. I do not know what is causing this situation in the react-i8next library.

@stale
Copy link

stale bot commented Oct 15, 2023

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the stale label Oct 15, 2023
@stale stale bot removed the stale label Feb 5, 2024
@odeyal0
Copy link

odeyal0 commented Feb 5, 2024

Similar problem in safari (verison in console)
image

Simple example:
https://codesandbox.io/p/devbox/i18-next-native-function-bug-2srdcz

@adrai
Copy link
Member

adrai commented Feb 5, 2024

sorry, but I'm not able to reproduce the issue with your codesandbox example
image

@odeyal0
Copy link

odeyal0 commented Feb 6, 2024

Looks like this issue libwebkit2gtk-4.0-37=2.40.5-1 only... (maybe some another versions)
Newer libwebkit2gtk has no this problem.

Reproducing issue on debian-11.7.0:
run sudo apt install libwebkit2gtk-4.0-37=2.40.5-1~bed11u1 libjavascriptcoregtk-4.0-18=2.40.5-1~deb11u1 and open usr/lib/x86_64-linux-gnu/webit2gtk-4.0/MiniBrowser and test my sandbox

libwebkit2gtk-4.0-37=2.40.5-1 is latest for some OS like AstraLinux and it's needed for tauri apps.

And if you open devtools on test issue will not be reproducing)

@odeyal0
Copy link

odeyal0 commented Feb 8, 2024

Btw, temporary fix (useTranslation wrapper, 'static' and 'backend' - my namespaces):

import { useMemo } from 'react';
import type { FallbackNs, UseTranslationOptions } from 'react-i18next';
import { useTranslation as useTranslationi18Next } from 'react-i18next';

import type { KeyPrefix, TFunction } from 'i18next';
import type { $Tuple } from 'react-i18next/helpers';

export const useTranslation: typeof useTranslationi18Next = <
  Ns extends
    | 'static'
    | 'backend'
    | $Tuple<'static' | 'backend'>
    | undefined = undefined,
  KPrefix extends KeyPrefix<FallbackNs<Ns>> = undefined,
>(
  ns?: Ns,
  options?: UseTranslationOptions<KPrefix>,
) => {
  const { t: tI18Next, ...other } = useTranslationi18Next<Ns, KPrefix>(
    ns,
    options,
  );

  const t = useMemo<TFunction<FallbackNs<Ns>>>(() => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const t = (...args: any) => {
      const res = tI18Next(...args);

      return typeof res === 'function' ? res.call(null, ...args) : res;
    };
    t.$TFunctionBrand = tI18Next.$TFunctionBrand;

    return t;
  }, [tI18Next]);

  return { t, ...other };
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants