ivanhofer/typesafe-i18n-demo-sveltekit

[HELP] page.ts setLocale loading wrong dictionary

Closed this issue · 1 comments

I'm having problems using the library with data-sveltekit-preload-data different from "off". In this example "hover" has been used, the problem is present with "tap" too. What happens is:

  1. hooks.server.ts sets
    event.locals.locale = locale; event.locals.LL = L[locale];
  2. current route page.ts sets
    const { locale } = await parent(); setLocale(locale);
  3. page loads
    *Now page is in English*
  4. while I'm on the page I change the locale using the same implementation of LocaleSwitcher from this project
    *Now page is in Spanish*
  5. I hover a link on the page pointing to a different route -> the interface goes back to English!

What happens is that preloading the route causes:

  1. server runs its code, hooks has not been triggered so it has the old locale
  2. the page.ts sets the locale with setLocale(locale) applying the old locale
  3. the interface gets refreshed with the wrong locale
    The video below shows such behaviour.

Do you have any idea on how to fix this? Obviously keeping the preload feature of sveltekit.

Registrazione.schermo.2023-06-06.alle.22.31.14.mov

There were some points to fix:
LocaleSwitcher was missing the await invalidateAll() but this was removed because the LocaleSwitcher was not working as expected. Using the same implementation of the example, using the $locale store to do che check if (!newLocale || currentLocale === newLocale) return; was not working after 2 consecutives locale switch. For my project the LocaleSwitcher is the only component that can change the language so I fixed it by adding in LocaleSwitcher.svelte:

let currentLocale = get(locale);
const switchLocale = async (newLocale: Locales, updateHistoryState = true) => {
	if (!newLocale || currentLocale === newLocale) return;
        currentLocale = newLocale;
        ...same implementation
        await invalidateAll();
}