Jgarnie
Jgarnie

Reputation: 489

i18n using keys as object keys instead of string

I have a translations constant that holds all the keys, that way I can access the translations by typing the key so it avoids mistakes.

however I am experiencing an issue whenever I am using the translations imported from that Translations file.

i18next::translator: missingKey en-US translations Phone Phone

my i18n file looks like:

import i18n from 'i18next'
import LanguageDetector from 'i18next-browser-languagedetector'
import moment from 'moment'

import {TRANSLATION} from './translations'

i18n.use(LanguageDetector).init({
  // we init with resources
  resources: {
    en: {
      translations: TRANSLATION.EN,
    },
  },
  fallbackLng: 'en-US',
  debug: process.env.NODE_ENV === 'development',

  // have a common namespace used around the full app
  ns: ['translations'],
  defaultNS: 'translations',
  keySeparator: false, // we use content as keys
  interpolation: {
    escapeValue: false, // not needed for react!!
    formatSeparator: ',',
    format: function(value, formatting, lng) {
      if (value instanceof Date) return moment(value).format(formatting)
      return value.toString()
    },
  },
  react: {
    wait: true,
  },
})

export default i18n

the file with the keys that I am using on the form

export const TRANSLATION = {

  EN:{
    phone: 'Phone',
  }
}

the component where I am using the Keys:

import i18n, {T_KEYS} from '@/services/i18n'

const Component=()=>{
return(
   <Form.Item
            name="phone"
            label={i18n.t(T_KEYS.phone)}
            rules={rules.phone}
          >
            <Input />
          </Form.Item>

)

I believe that for some reason the component is being rendered before the translations keys have accessed, so the Keys are missing and the message is displayed but I am not 100% sure, I tried adding Object.keys(TRANSLATIONS.EN) && before i18n.use(LanguageDetector).init({, but it des not seem to solve the situation, I was wondering if anyone had a similar issue or idea since after browsing through documentation and repository I couldn't find any answer to what is happening.

thanks in advance

Upvotes: 1

Views: 3237

Answers (1)

Joaquin86
Joaquin86

Reputation: 116

the problem for this issue for those of you searching for a answer, is that when using the T_KEYS.phone, we are sending the key Phone, that does not exist on our translations file, this is causing the error with the translations.

Upvotes: 1

Related Questions