square / svelte-store

528 stars 36 forks source link

Can a regular svelte-store become Loadable? #54

Closed sureshjoshi closed 1 year ago

sureshjoshi commented 1 year ago

I'm using a 3rd party library which exposes a Svelte store, and I was wondering if it could be modified or consumed by the Loadable stores, while maintaining the same level of reactivity?

This i18n library (https://github.com/kaisermann/svelte-i18n) exposes a locale store, and I was trying to use persisted to clean up my local storage handling for languages. However, when I change my language, nothing seems to happen (e.g. the cascade of store updates don't appear to occur).

So, this got me thinking I was supposed to wrap that i18n store in a derived or something else first? Or somehow pull it into this Loadable ecosystem?

sureshjoshi commented 1 year ago

The way I've currently had "success" (I use that term lightly), is like this:

# File where I declare some i18n stuff
import { locale } from "svelte-i18n";
export const loadableLocale = derived(locale, ($locale) => $locale);
export const persistedLocale = persisted(loadableLocale, LOCAL_STORAGE_KEY, { reloadable: true });

# language-switcher.svelte
function handleLanguageChange(language: string) {
    locale.set(language);
    persistedLocale.reload();
}

Needing to set the original locale object, and then calling reload on the persisted store feels wrong.

Note: The reason I'm trying to do this in the first place is that downstream, I have a network call which kicks off when the locale changes.

sureshjoshi commented 1 year ago

Okay, so, apparently my intellisense was borked - so while I thought the persisted repos were writable, VSCode told me I was wrong.

This is my current workaround, which seems to solve most of my grief. I just work "backwards", and use the persisted store as my main writable object, and the 3rd party lib's locale store gets updated in a subscribe.

persistedLocale.subscribe((value) => {
  locale.set(value);
});

Arguably, this is a better solution anyways - as it lets me abstract away the underlying library from the 2-3 places it was in my code 🤷🏽