sveltekit-i18n / lib

Internationalization library built for SvelteKit.
MIT License
447 stars 28 forks source link

Reasonable way to avoid locale resetting on preload? #143

Closed henrikvilhelmberglund closed 10 months ago

henrikvilhelmberglund commented 10 months ago

I have a few buttons for selecting the user language which change the $locale store to the locale string. I had an issue where $locale would get reset to whatever initLocale was in the +layout.js when hovering over links (preload) and when changing the route.

I fixed(?) it by using the following code:

const initLocale = get(locale) ? get(locale) : "en"; // get from cookie, user session, ...

await loadTranslations(initLocale, pathname); 

which seems to work as it uses the $locale store value if it exists, otherwise "en" as a default. (Should probably use cookies/localstorage for this later)

My main question is, is there a better way to do this? I'm very new to i18n.

jarda-svoboda commented 10 months ago

Hi @henrikvilhelmberglund! Your solution is quite tricky as the locale store is shared between users on server. Recommended is to use cookies to keep user’s preferred language.. see example here.