xiCO2k / laravel-vue-i18n

Allows to connect your `Laravel` Framework translation files with `Vue`.
MIT License
594 stars 49 forks source link

Translation set to null if key doesn't exist #129

Closed Majkie closed 1 year ago

Majkie commented 1 year ago

In our project, we don't have translations for simple strings in en_US.json, only in any other language. So, when we use wTrans within our code, the value is initially set to the key, but then once loadLanguageAsync finishes it is set to null by this piece of code because the translation key doesn't exist.

Here is a test to reproduce our issue.

it('checks if watching translation works if key does not exist', async () => {
    await global.mountPlugin('<div />');

    const translated = wTrans('Welcome to the Vue!');

    expect(translated.value)
        .toBe('Welcome to the Vue!');

    await loadLanguageAsync('en');

    // Fails because translated.value now equals to null
    expect(translated.value)
        .toBe('Welcome to the Vue!');
})

One possible solution I found is by having a watchEffect within wTrans, but I have no idea if it can result in some performance issues, so it would be wise to check first. Hopefully, you will find a solution.

wTrans(key: string, replacements: ReplacementsInterface = {}): ComputedRef<string> {
  watchEffect(() => {
    this.activeMessages[key] = this.findTranslation(key) || this.findTranslation(key.replace(/\//g, '.')) || key
  })

  return computed(() => this.makeReplacements(this.activeMessages[key], replacements))
}
xiCO2k commented 1 year ago

Thanks for the debug.

Do you want to do a PR with that solution?

Thanks.