Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Issue when calling the loadLanguageAsync in parallel. #156

Merged
merged 1 commit into from
Jan 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading