Spec Registry
Help your agents use open-source better. Learn more.
Find usage specs for your project’s dependencies
- Author
- tessl
- Last updated
- Spec files
npm-svelte
Describes: npm/svelte
- Description
- A cybernetically enhanced web application framework that compiles to highly optimized JavaScript with reactive state management and component-based architecture.
- Author
- tessl
- Last updated
stores.md docs/
1# Store System23Svelte's store system provides reactive state management that can be shared across multiple components. Stores are particularly useful for application-wide state that needs to persist across component boundaries.45## Capabilities67### writable89Creates a store with both read and write capabilities. Subscribers are notified when the value changes.1011```typescript { .api }12/**13* Create a writable store that allows both updating and reading by subscription14* @param value - Initial value (optional)15* @param start - Function called when first subscriber subscribes16* @returns Writable store instance17*/18function writable<T>(value?: T, start?: StartStopNotifier<T>): Writable<T>;19```2021**Usage Examples:**2223```typescript24import { writable } from "svelte/store";2526// Basic writable store27const count = writable(0);2829// Store with initial value30const user = writable({ name: "Alice", age: 30 });3132// Store with start/stop logic33const time = writable(new Date(), (set) => {34const interval = setInterval(() => {35set(new Date());36}, 1000);3738// Cleanup function called when last subscriber unsubscribes39return () => clearInterval(interval);40});4142// Using stores in components43count.subscribe(value => {44console.log("Count:", value);45});4647// Update store values48count.set(5);49count.update(n => n + 1);5051// Auto-subscribe in Svelte components with $52// let currentCount = $count; // Automatically subscribes53```5455### readable5657Creates a read-only store. The value can only be set from within the store's start function.5859```typescript { .api }60/**61* Creates a readable store that allows reading by subscription62* @param value - Initial value (optional)63* @param start - Function called when first subscriber subscribes64* @returns Readable store instance65*/66function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T>;67```6869**Usage Examples:**7071```typescript72import { readable } from "svelte/store";7374// Static readable store75const appName = readable("My App");7677// Dynamic readable store78const mousePosition = readable({ x: 0, y: 0 }, (set) => {79const handleMouseMove = (event) => {80set({ x: event.clientX, y: event.clientY });81};8283document.addEventListener("mousemove", handleMouseMove);8485return () => {86document.removeEventListener("mousemove", handleMouseMove);87};88});8990// WebSocket store example91const websocketStore = readable(null, (set) => {92const ws = new WebSocket("ws://localhost:8080");9394ws.onmessage = (event) => {95set(JSON.parse(event.data));96};9798return () => {99ws.close();100};101});102```103104### derived105106Creates a store whose value is computed from one or more other stores. Updates automatically when dependencies change.107108```typescript { .api }109/**110* Derived store that computes its value from other stores111* @param stores - Single store or array of stores to derive from112* @param fn - Function that computes the derived value113* @param initial_value - Initial value before first computation114* @returns Readable derived store115*/116function derived<S extends Stores, T>(117stores: S,118fn: (values: StoresValues<S>) => T,119initial_value?: T120): Readable<T>;121122/**123* Derived store with async computation124* @param stores - Single store or array of stores to derive from125* @param fn - Function that computes value with set callback126* @param initial_value - Initial value before first computation127* @returns Readable derived store128*/129function derived<S extends Stores, T>(130stores: S,131fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void,132initial_value?: T133): Readable<T>;134```135136**Usage Examples:**137138```typescript139import { writable, derived } from "svelte/store";140141const firstName = writable("John");142const lastName = writable("Doe");143144// Simple derived store145const fullName = derived(146[firstName, lastName],147([first, last]) => `${first} ${last}`148);149150// Single store derivation151const doubled = derived(count, n => n * 2);152153// Derived with initial value154const greeting = derived(155fullName,156name => `Hello, ${name}!`,157"Hello, Guest!"158);159160// Async derived store161const userProfile = derived(162userId,163(id, set) => {164if (!id) {165set(null);166return;167}168169const controller = new AbortController();170171fetch(`/api/users/${id}`, { signal: controller.signal })172.then(r => r.json())173.then(profile => set(profile))174.catch(err => {175if (!controller.signal.aborted) {176console.error("Failed to fetch user:", err);177set(null);178}179});180181return () => controller.abort();182},183null184);185186// Complex derived computation187const statistics = derived(188[users, posts, comments],189([userList, postList, commentList]) => ({190totalUsers: userList.length,191totalPosts: postList.length,192totalComments: commentList.length,193avgCommentsPerPost: commentList.length / postList.length || 0194})195);196```197198### get199200Synchronously retrieves the current value from a store without subscribing.201202```typescript { .api }203/**204* Get the current value from a store by subscribing and immediately unsubscribing205* @param store - Store to get value from206* @returns Current store value207*/208function get<T>(store: Readable<T>): T;209```210211**Usage Examples:**212213```typescript214import { writable, get } from "svelte/store";215216const count = writable(42);217218// Get current value without subscribing219const currentCount = get(count);220console.log(currentCount); // 42221222// Useful for one-off operations223function logCurrentState() {224console.log({225count: get(count),226user: get(user),227settings: get(settings)228});229}230231// In event handlers where you need current value232function handleClick() {233const current = get(count);234if (current > 10) {235// Do something236}237}238```239240### readonly241242Creates a read-only version of a writable store, preventing external modifications.243244```typescript { .api }245/**246* Takes a store and returns a new one derived from the old one that is readable247* @param store - Store to make readonly248* @returns Readonly version of the store249*/250function readonly<T>(store: Readable<T>): Readable<T>;251```252253**Usage Examples:**254255```typescript256import { writable, readonly } from "svelte/store";257258// Internal writable store259const _settings = writable({260theme: "light",261language: "en"262});263264// Public readonly interface265export const settings = readonly(_settings);266267// Internal functions can still modify268export function updateTheme(theme) {269_settings.update(s => ({ ...s, theme }));270}271272export function updateLanguage(language) {273_settings.update(s => ({ ...s, language }));274}275276// External consumers can only read277// settings.set(...) // This would cause a TypeScript error278```279280### Store Conversion Utilities281282Convert between Svelte 5 runes and stores for interoperability.283284```typescript { .api }285/**286* Create a store from a function that returns state287* @param get - Function that returns current value288* @param set - Optional function to update value (makes it writable)289* @returns Store (readable or writable based on parameters)290*/291function toStore<V>(get: () => V, set: (v: V) => void): Writable<V>;292function toStore<V>(get: () => V): Readable<V>;293294/**295* Convert a store to an object with a reactive current property296* @param store - Store to convert297* @returns Object with current property298*/299function fromStore<V>(store: Writable<V>): { current: V };300function fromStore<V>(store: Readable<V>): { readonly current: V };301```302303**Usage Examples:**304305```typescript306import { toStore, fromStore } from "svelte/store";307308// Convert rune state to store309let count = $state(0);310const countStore = toStore(311() => count,312(value) => count = value313);314315// Convert store to rune-like object316const settings = writable({ theme: "light" });317const settingsRune = fromStore(settings);318319// Use like rune state320$effect(() => {321console.log("Theme:", settingsRune.current.theme);322});323324// Update through original store325settings.update(s => ({ ...s, theme: "dark" }));326```327328## Types329330```typescript { .api }331interface Readable<T> {332/**333* Subscribe to store changes334* @param run - Function called with current value and on changes335* @param invalidate - Optional cleanup function336* @returns Unsubscribe function337*/338subscribe(run: Subscriber<T>, invalidate?: () => void): Unsubscriber;339}340341interface Writable<T> extends Readable<T> {342/**343* Set the store value and notify subscribers344* @param value - New value to set345*/346set(value: T): void;347348/**349* Update the store value using a function and notify subscribers350* @param updater - Function that receives current value and returns new value351*/352update(updater: Updater<T>): void;353}354355type Subscriber<T> = (value: T) => void;356type Unsubscriber = () => void;357type Updater<T> = (value: T) => T;358359type StartStopNotifier<T> = (360set: (value: T) => void,361update: (fn: Updater<T>) => void362) => void | (() => void);363364type Stores = Readable<any> | [Readable<any>, ...Array<Readable<any>>] | Array<Readable<any>>;365366type StoresValues<T> = T extends Readable<infer U>367? U368: { [K in keyof T]: T[K] extends Readable<infer U> ? U : never };369```370371## Best Practices3723731. **Use stores for global state**: Perfect for user authentication, app settings, shopping carts3742. **Prefer derived over manual subscriptions**: Let Svelte handle the reactivity3753. **Clean up subscriptions**: Always call the unsubscriber function to prevent memory leaks3764. **Use readonly for public APIs**: Expose readonly stores when you want to control mutations3775. **Consider custom stores**: Create specialized stores with domain-specific methods3786. **Lazy loading**: Use start/stop notifiers to manage expensive resources like WebSocket connections