0

I have two JSON files with names 'en.json' and 'fr.json' which has all the translations.

en.json

{ "General.LearnMore": "Learn More" }

I have a mobx store (.ts file) and I want to access intl.formatMessage() in that class.

It is easier in functional components. I can use useIntl() hook but how can I do the same in a store file (non-component).

When I write the below code in store file:

const messages = defineMessages({
  SMS: {
    id: 'General.LearnMore',
  },
});

const cache = createIntlCache();
const locale = localStorage.getItem('locale')!;
const intl = createIntl({ locale, messages: {} }, cache);
console.log(intl.formatMessage({ id: 'General.select' }));
console.log(intl.formatMessage({ id: messages.sms.id }));

It gives this error:

enter image description here

What I am missing and How can I fix this? Please help!

newbie
  • 530
  • 1
  • 9
  • 36

1 Answers1

0

In createIntl you pass an empty object to messages so intl doesn't find the ids.

To fix, import the en.json:

import enMessages from '../path/to/en.json'

and pass it on cretaeIntl:

const intl = createIntl({ locale, messages: enMessages }, cache);

If you created the messages object with defineMessages just for the purpose of getting value from intl - you can delete it, it doesn't give access to the key-value files (createIntl doesn't automatically get the data of intlProvider, it needs full initialition with locale and messages)

If you want the messages to be updated every time the locale is switched so here a good example

Hope this will help!

misolo
  • 981
  • 1
  • 12
  • 16