Skip to content

Commit 390e70c

Browse files
authored
fix: Issue when calling the loadLanguageAsync in parallel. (#156)
Fixes #119
1 parent eec761d commit 390e70c

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/index.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ export class I18n {
132132
/**
133133
* Stores the loaded languages.
134134
*/
135-
private static loaded: LanguageInterface[] = []
135+
public static loaded: LanguageInterface[] = []
136136

137137
// Stores options for the current instance
138138
private options: OptionsInterface
@@ -317,7 +317,7 @@ export class I18n {
317317
}
318318

319319
const data: LanguageInterface = { lang, messages }
320-
I18n.loaded.push(data)
320+
this.addLoadedLang(data)
321321

322322
return this.setLanguage(data)
323323
}
@@ -327,12 +327,27 @@ export class I18n {
327327
this.fallbackMessages[key] = value
328328
}
329329

330-
I18n.loaded.push({
330+
this.addLoadedLang({
331331
lang: this.options.fallbackLang,
332332
messages
333333
})
334334
}
335335

336+
/**
337+
* Adds to the array of loaded languages.
338+
*/
339+
addLoadedLang(data: LanguageInterface): void {
340+
const foundIndex = I18n.loaded.findIndex((item) => item.lang === data.lang)
341+
342+
if (foundIndex !== -1) {
343+
I18n.loaded[foundIndex] = data
344+
345+
return
346+
}
347+
348+
I18n.loaded.push(data)
349+
}
350+
336351
/**
337352
* Sets the language messages to the activeMessages.
338353
*/

test/translate.test.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { mount } from '@vue/test-utils'
2-
import { i18nVue, trans, trans_choice, loadLanguageAsync, reset, getActiveLanguage, isLoaded, wTrans } from '../src'
2+
import { i18nVue, trans, trans_choice, loadLanguageAsync, reset, getActiveLanguage, isLoaded, wTrans, I18n } from '../src'
33
import { reset as resetLoader } from '../src/loader'
44

55
beforeEach(() => reset());
@@ -109,6 +109,21 @@ it('loads a lang', async () => {
109109
expect(wrapper.html()).toBe('<h1>Bem-vindo, Francisco!</h1>')
110110
})
111111

112+
it('only keep one item for each lang even with multiple calls of the `loadLanguageAsync`', async () => {
113+
const wrapper = await global.mountPlugin();
114+
115+
expect(I18n.loaded.length).toBe(1);
116+
117+
// Purpose call multiple times to replicate a multiple call.
118+
await Promise.all([
119+
loadLanguageAsync('en'),
120+
loadLanguageAsync('en'),
121+
]);
122+
123+
expect(I18n.loaded.length).toBe(2);
124+
125+
})
126+
112127
it('returns the active lang', async () => {
113128
await global.mountPlugin();
114129

0 commit comments

Comments
 (0)