Not all application state belongs inside your application's component hierarchy. Sometimes, you'll have values that need to be accessed by multiple unrelated components, or by a regular JavaScript module.
In Svelte, we do this with *stores*. A store is simply an object with a `subscribe` method that allows interested parties to be notified whenever the store value changes. In `App.svelte`, `count` is a store, and we're setting `count_value` in the `count.subscribe` callback.
In Svelte, we do this with *stores*. A store is simply an object with a `subscribe` method that allows interested parties to be notified whenever the store value changes. In `App.svelte`, `count` is a store, and we're setting `countValue` in the `count.subscribe` callback.
Click the `stores.js` tab to see the definition of `count`. It's a *writable* store, which means it has `set` and `update` methods in addition to `subscribe`.
@ -8,7 +8,7 @@ Start by declaring `unsubscribe` in `App.svelte`:
```js
const unsubscribe = count.subscribe(value => {
count_value = value;
countValue = value;
});
```
> Calling a `subscribe` method returns an `unsubscribe` function.
@ -23,16 +23,16 @@ You now declared `unsubscribe`, but it still needs to be called, for example thr
import Decrementer from './Decrementer.svelte';
import Resetter from './Resetter.svelte';
let count_value;
let countValue;
const unsubscribe = count.subscribe(value => {
count_value = value;
countValue = value;
});
onDestroy(unsubscribe);
</script>
<h1>The count is {count_value}</h1>
<h1>The count is {countValue}</h1>
```
It starts to get a bit boilerplatey though, especially if your component subscribes to multiple stores. Instead, Svelte has a trick up its sleeve — you can reference a store value by prefixing the store name with `$`: