Js-lingui: t macro with variable id extracted as message with undefined id

Created on 7 Dec 2020  路  9Comments  路  Source: lingui/js-lingui

Describe the bug
t({id: foo}) calls are being extracted with undefined message id

#~ messages.po

#: src/path/file.tsx:##
msgid "undefined"
msgstr ""

To Reproduce

// src/path/file.tsx

import {t} from "@lingui/macro"

const foo = t`foo`

const Component = () => {
  const text = t({id: foo})

  return <span>{text}</span>
}

Expected behavior
No messages.po changes

Additional context
Dependencies

    "@lingui/cli": "3.2.3",
    "@lingui/loader": "3.2.3",
    "@lingui/macro": "3.2.3",
    "@lingui/react": "3.2.3",
    "babel-plugin-macros": "2.8.0",
    "react-scripts": "3.4.3",
    "typescript": "3.9.7",
invalid

All 9 comments

No has sense to use t inside other t, mate. just use:

import {t} from "@lingui/macro"

const Component = () => {
  const text = t`foo`

  return <span>{text}</span>
}

@semoal it's needed for static translations, e.g. outside of react component

You definitely shouldn't use t macro twice. If you want to use "lazy translations", use defineMessage instead.

import {t} from "@lingui/macro"

const foo = defineMessage({ message: "foo" })

const Component = () => {
  const text = t({id: foo})

  return <span>{text}</span>
}

Still, there's a bug that t({ id: foo }) is extracted as undefined. It should be simply ignored.

Note regarding t macro usage: I came to this in order to get a translation as string:

const lazyId = t`foo`

const Foo = () => {
  const label = <Trans id={lazyId} />

  return <Bar label={label} /> // error, label prop should be a string, not a React element
}

You need to use defineMessage for that

Actually, there're two mistakes in your example

// Mistake #1: Use `defineMessage` for lazy translations
const lazyId = defineMessage({ message: `foo` })

const Foo = () => {
  // Mistake #2: Use `i18._` or `t` macro if you want to get string , not React element
  const { i18n } = useLingui()
  const label = i18n._(lazyId)

  return <Bar label={label} /> // error, label prop should be a string, not a React element
}

I see how I misused that API, however I've digged into the codebase a bit and found a fix for initial problem with undefined msgids.

Hope you don't mind checking it out 馃槂

I don't mind at all! Thank you for fixing it 馃憤

Was this page helpful?
0 / 5 - 0 ratings