Grzes Slania
Grzes Slania

Reputation: 602

Update svelte store while subscribed to another

I'm not sure this is possible but I need to update a svelte store while it is subscribed to another store.
Here's an example of what I mean.
Is this doable or what would be the best solution?

import { languageStore, appConfig } from "$lib/stores.js";

let productAppConfig;

// Subscribe to this store when language changes
languageStore.subscribe(lang => {
    init({
        fallbackLocale: 'en',
        initialLocale: lang,
    });
    // I get an error whenever I try to update this store inside here
    // appConfig.update()
});

// Set up product app configuration
productAppConfig = {
    title: 'Bike',
    video: {
        id: 'y_QNep4T17M', // YouTube video id
        steps: [
            {
                title: $json('bike.videoSteps')[0].title,
                seek: 10
            }...
        ]
    },
    locale: 'bike',
    glossary: true  
}
onMount( () => {
    appConfig.update( ( value ) => { 
        return value = productAppConfig 
    }) 
})

Upvotes: 0

Views: 580

Answers (1)

brunnerh
brunnerh

Reputation: 184366

In general, if one store depends on another, it should be a derived store. In this case, if the config is dependent on localization, it should derive from that. If other stores are needed as data sources, e.g. some base config, they can be included as well.

So you get something like:

const appConfig = derived(
  [languageStore, baseConfigStore],
  ([lang, config]) => {
    // create new app config object using `lang` & `config` and return it
  }
);

With this, appConfig is read-only and will update whenever the stores it is based on are changed.

Upvotes: 1

Related Questions