diff --git a/src/index.ts b/src/index.ts index 25af773..49317df 100644 --- a/src/index.ts +++ b/src/index.ts @@ -132,7 +132,7 @@ export class I18n { /** * Stores the loaded languages. */ - private static loaded: LanguageInterface[] = [] + public static loaded: LanguageInterface[] = [] // Stores options for the current instance private options: OptionsInterface @@ -317,7 +317,7 @@ export class I18n { } const data: LanguageInterface = { lang, messages } - I18n.loaded.push(data) + this.addLoadedLang(data) return this.setLanguage(data) } @@ -327,12 +327,27 @@ export class I18n { this.fallbackMessages[key] = value } - I18n.loaded.push({ + this.addLoadedLang({ lang: this.options.fallbackLang, messages }) } + /** + * Adds to the array of loaded languages. + */ + addLoadedLang(data: LanguageInterface): void { + const foundIndex = I18n.loaded.findIndex((item) => item.lang === data.lang) + + if (foundIndex !== -1) { + I18n.loaded[foundIndex] = data + + return + } + + I18n.loaded.push(data) + } + /** * Sets the language messages to the activeMessages. */ diff --git a/test/translate.test.ts b/test/translate.test.ts index 3265f42..6e7715c 100644 --- a/test/translate.test.ts +++ b/test/translate.test.ts @@ -1,5 +1,5 @@ import { mount } from '@vue/test-utils' -import { i18nVue, trans, trans_choice, loadLanguageAsync, reset, getActiveLanguage, isLoaded, wTrans } from '../src' +import { i18nVue, trans, trans_choice, loadLanguageAsync, reset, getActiveLanguage, isLoaded, wTrans, I18n } from '../src' import { reset as resetLoader } from '../src/loader' beforeEach(() => reset()); @@ -109,6 +109,21 @@ it('loads a lang', async () => { expect(wrapper.html()).toBe('

Bem-vindo, Francisco!

') }) +it('only keep one item for each lang even with multiple calls of the `loadLanguageAsync`', async () => { + const wrapper = await global.mountPlugin(); + + expect(I18n.loaded.length).toBe(1); + + // Purpose call multiple times to replicate a multiple call. + await Promise.all([ + loadLanguageAsync('en'), + loadLanguageAsync('en'), + ]); + + expect(I18n.loaded.length).toBe(2); + +}) + it('returns the active lang', async () => { await global.mountPlugin();