javascript / intermediate
Snippet
Custom Writable Stores with Encapsulated Logic
Custom stores allow you to hide the internal 'set' and 'update' methods, exposing only domain-specific actions. This prevents external components from setting invalid states and keeps logic centralized.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { writable } from 'svelte/store';function createCounter() {const { subscribe, set, update } = writable(0);return {subscribe,increment: () => update(n => n + 1),decrement: () => update(n => n - 1),reset: () => set(0)};}export const counter = createCounter();
svelte
Breakdown
1
const { subscribe, set, update } = writable(0);
Destructure the store methods from a new writable store initialized at 0.
2
return { subscribe, increment: ... }
Return an object that includes 'subscribe' but replaces 'set' and 'update' with specific methods.