A store is simply an object with a subscribe method that allows interested parties to be notified whenever the store value changes:
<script>
let countValue;
const unsubscribe = count.subscribe(value => {
count_value = value;
});
onDestroy(unsubscribe);
</script>
<h1>The count is {count_value}</h1>
Update the stored value:
<script>
function increment() {
count.update(n => n + 1)
}
</script>
Set a value:
<script>
function reset() {
count.set(0);
}
</script>
Usage
Use auto-subscription to get rid of subscribe and onDestroy methods:
<script>
import { storeValue } from './AnotherComponent'
// ...other imports come after
</script>
<h1>The count is {$storeValue}</h1>
Readable store
<script>
export const time = readable(new Date(), function start(set) {
// Implementation
set()
return function stop() {
// Implementation
}
})
</script>
Writable store
<script>
import { writable } from 'svelte/store';
const count = writable(0, () => {
console.log('got a subscriber');
return () => console.log('no more subscribers');
});
</script>
Derived store
…from another store.
<script>
import { derived } from 'svelte/store';
const delayed = derived(time, ($a, set) => {
setTimeout(() => set($a), 1000);
}, 'one moment...');
// or (read-only derived):
const elapsed = derived(time, $time =>
Math.round(($time - start) / 1000)
);
</script>
Custom store
// store.js
import { writable } from 'svelte/store';
function createCount() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1),
decrement: () => update(n => n - 1),
reset: () => set(0)
};
}
export const count = createCount();
In the component:
<script>
import { count } from './store.js';
</script>
<h1>The count is {$count}</h1>
<button on:click={count.increment}>+</button>
<button on:click={count.decrement}>-</button>
<button on:click={count.reset}>reset</button>
Top comments (0)