lib icon indicating copy to clipboard operation
lib copied to clipboard

Translations in stores and objects does not change when locale is changed

Open ToP29 opened this issue 2 years ago • 3 comments

When i change locale like this locale.set(newLocale), the translations change only in some places. If i have translations in some store, they do not change. I have layout store which has setHeader method and if i call it like this setHeader({ title: $t('settings.title') }); and then change locale, this tranlations does not change (until page is refreshed). Same problem is happening when I create array of objects and key in this object is translation, when i render components from this object, the translations will not update after locale change. Object example:

const navItems= [
    {
      label: $t('home.title'),
      target: '/home',
    },
    {
      label: $t('about.title'),
      target: '/about',
    },
]

Usage example:

{#each navItems as item}
    <NavButton
       {...item}
    />
 {/each}

In NavButton i am using the passed prop like this: <span>{label}</span>

I think that it realtime translates only things in svelte component it html section within $t() function, but if you have translation stored somewhere else and in component you only want to render it without $t() than it works only after page refresh, not on locale change

ToP29 avatar Jun 08 '22 12:06 ToP29

Not tested yet, but I’d try something like:

locale.subscribe(() => {
  setHeader({ title: $t('settings.title') });
})

jarda-svoboda avatar Jun 08 '22 14:06 jarda-svoboda

Yes this will work, but wouldnt it be better to implement it like in svelte-i18n? So that every translation no matter where or how it was defined, will translate when locale changes?

ToP29 avatar Jun 08 '22 14:06 ToP29

I am trying this same exact thing, but can't figure out how to get an array from $t

kevin192291 avatar Jun 19 '22 15:06 kevin192291

Can confirm that

locale.subscribe(()

Works.

That being said, +1 to this feature would be great to use like

const sample =  [
    {
      label: $t('some.thing', 1),
      value: 33,
    },
    {
      label: $t('some.thing', 3),
      value: 42,
    },
]

or maybe even:

const sample =  [
    {
      label: t.get('some.thing', 1),
      value: 33,
    },
    {
      label: t.get('some.thing', 3),
      value: 42,
    },
]

And have it update automatically. I can see how this would be quite complicated to implement but it would be useful when feeding dynamic data that has params and needs to be translated to a dropdown for example.

lucas-subli avatar Jul 01 '23 17:07 lucas-subli

I think you should just use:

$: navItems = [
    {
      label: $t('home.title'),
      target: '/home',
    },
    {
      label: $t('about.title'),
      target: '/about',
    },
];

in your Svelte file..

jarda-svoboda avatar Jul 07 '23 13:07 jarda-svoboda