3

I am using create-react-app and react-intl and I am having the issue that I am fetching data from an API and I want this data to be translated into several languages <FormattedMessage {...messages['fetched-id']} />component from react.intl Because I can't 100% rely on the API output it can happen that some id's returned by the API are not defined in my translation files. What happens in the end is that react-intl crashes because of an unknown id (Error: [@formatjs/intl] An id must be provided to format a message)

Now I wanted to know if there is a way with CRA that I can prevent the react-intl lib from crashing and to render a fallback in this case (which can be the id that has been passed - in the same manner like react-i18next does it).

I saw in other posts that it's recommended to use the babel-plugin-formatjs together with craco to fix this issue (https://github.com/formatjs/formatjs/issues/1901). Unfortunately this didn't work for me.

Example:

I am using:

defineMessages({
  guitar: {
    id: 'app.components.Text.guitar',
    defaultMessage: 'Guitar',
  }
})

and in my en.json file I have my english translations :

"app.components.Text.guitar": "Guitar",

calling <FormattedMessage {...messages['<instrument-name>']} />

and now I am fetching instruments from the server and I want to translation them into several languages. If now for example the server returns an instrument name that is not defined via defineMessages or in the en.json file then it will complain that a id must be provided. And I am wondering if in that case I can prevent it to crash and just render the that was passed instead? Hope this was somehow understandable

1 Answers1

0

Hopefully I'm not misunderstanding what you say you are receiving from your server. You can check if the message object has an id property first, then either spread it in, or some fallback string object.

<FormattedMessage
  {...(messages[idFromServer]?.id ? messages[idFromServer] : messages.fallback)}
/>
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Thanks for replying. I updated my question to make it more clear what I was talking about – Sebastian G Jun 19 '21 at 10:51
  • @SebastianG I saw your edits, but my perceived understanding of your question remains unchanged. Have you tried my solution, or variation of it, to first check if the translation key actually returns a string object with an `id` property? – Drew Reese Jun 21 '21 at 15:48