Skip to content

Commit

Permalink
fix: Issue when calling the loadLanguageAsync in parallel.
Browse files Browse the repository at this point in the history
  • Loading branch information
xiCO2k committed Jan 4, 2024
1 parent eec761d commit 5cd73a8
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
21 changes: 18 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -317,7 +317,7 @@ export class I18n {
}

const data: LanguageInterface = { lang, messages }
I18n.loaded.push(data)
this.addLoadedLang(data)

return this.setLanguage(data)
}
Expand All @@ -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.
*/
Expand Down
17 changes: 16 additions & 1 deletion test/translate.test.ts
Original file line number Diff line number Diff line change
@@ -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());
Expand Down Expand Up @@ -109,6 +109,21 @@ it('loads a lang', async () => {
expect(wrapper.html()).toBe('<h1>Bem-vindo, Francisco!</h1>')
})

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();

Expand Down

0 comments on commit 5cd73a8

Please sign in to comment.