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
- Revolutionary JavaScript framework and compiler that builds web applications without runtime overhead by compiling components at build time.
- Author
- tessl
- Last updated
store-management.md docs/
1# Store Management23Reactive state management system with readable, writable, and derived stores for application-wide state.45## Capabilities67### Writable Stores89Create stores that can be read from and written to by any part of your application.1011```javascript { .api }12/**13* Creates a writable store that allows both updating and reading by subscription14* @param value - Initial value15* @param start - Optional start/stop notifier function16* @returns Writable store instance17*/18function writable<T>(value?: T, start?: StartStopNotifier<T>): Writable<T>;1920interface Writable<T> extends Readable<T> {21/** Set value and inform subscribers */22set(this: void, value: T): void;23/** Update value using callback and inform subscribers */24update(this: void, updater: Updater<T>): void;25}2627interface Readable<T> {28/** Subscribe to value changes */29subscribe(this: void, run: Subscriber<T>, invalidate?: Invalidator<T>): Unsubscriber;30}3132type Subscriber<T> = (value: T) => void;33type Unsubscriber = () => void;34type Updater<T> = (value: T) => T;35type Invalidator<T> = (value?: T) => void;36```3738**Usage Examples:**3940```javascript41import { writable } from "svelte/store";4243// Basic writable store44const count = writable(0);4546// Subscribe to changes47const unsubscribe = count.subscribe(value => {48console.log('Count is now:', value);49});5051// Update the store52count.set(5);53count.update(n => n + 1);5455// Clean up subscription56unsubscribe();5758// Store with start/stop logic59const websocketStore = writable(null, (set) => {60const socket = new WebSocket('ws://localhost:8080');6162socket.onmessage = (event) => {63set(JSON.parse(event.data));64};6566return () => {67socket.close();68};69});70```7172### Readable Stores7374Create read-only stores that can be subscribed to but not directly modified.7576```javascript { .api }77/**78* Creates a readable store that allows reading by subscription79* @param value - Initial value80* @param start - Optional start/stop notifier function81* @returns Readable store instance82*/83function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T>;8485type StartStopNotifier<T> = (86set: (value: T) => void,87update: (fn: Updater<T>) => void88) => void | (() => void);89```9091**Usage Examples:**9293```javascript94import { readable } from "svelte/store";9596// Time store that updates every second97const time = readable(new Date(), (set) => {98const interval = setInterval(() => {99set(new Date());100}, 1000);101102return () => clearInterval(interval);103});104105// Mouse position store106const mousePosition = readable({ x: 0, y: 0 }, (set) => {107const handleMouseMove = (event) => {108set({ x: event.clientX, y: event.clientY });109};110111document.addEventListener('mousemove', handleMouseMove);112113return () => {114document.removeEventListener('mousemove', handleMouseMove);115};116});117```118119### Derived Stores120121Create stores whose values are computed from other stores.122123```javascript { .api }124/**125* Creates a derived store by synchronizing one or more readable stores126* @param stores - Input stores (single store or array)127* @param fn - Function to compute derived value128* @param initial_value - Optional initial value129* @returns Readable store with derived value130*/131function derived<S extends Stores, T>(132stores: S,133fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void,134initial_value?: T135): Readable<T>;136137function derived<S extends Stores, T>(138stores: S,139fn: (values: StoresValues<S>) => T,140initial_value?: T141): Readable<T>;142143type Stores = Readable<any> | [Readable<any>, ...Array<Readable<any>>] | Array<Readable<any>>;144type StoresValues<T> = T extends Readable<infer U> ? U : { [K in keyof T]: T[K] extends Readable<infer U> ? U : never };145```146147**Usage Examples:**148149```javascript150import { writable, derived } from "svelte/store";151152const firstName = writable('John');153const lastName = writable('Doe');154155// Simple derived store156const fullName = derived(157[firstName, lastName],158([first, last]) => `${first} ${last}`159);160161// Derived store with initial value162const greeting = derived(163fullName,164($fullName) => `Hello, ${$fullName}!`,165'Hello, World!'166);167168// Async derived store with set callback169const userProfile = derived(170userId,171($userId, set) => {172if (!$userId) {173set(null);174return;175}176177fetch(`/api/users/${$userId}`)178.then(res => res.json())179.then(set);180},181null182);183```184185### Store Utilities186187Utility functions for working with stores.188189```javascript { .api }190/**191* Makes a store readonly192* @param store - Store to make readonly193* @returns Readonly version of the store194*/195function readonly<T>(store: Readable<T>): Readable<T>;196197/**198* Gets the current value from a store by subscribing and immediately unsubscribing199* @param store - Store to get value from200* @returns Current store value201*/202function get<T>(store: Readable<T>): T;203```204205**Usage Examples:**206207```javascript208import { writable, readonly, get } from "svelte/store";209210const internalStore = writable(42);211212// Create readonly version for external use213export const publicStore = readonly(internalStore);214215// Get current value without subscribing216const currentValue = get(internalStore);217console.log('Current value:', currentValue);218219// Useful in event handlers220function handleClick() {221const currentCount = get(count);222console.log('Button clicked, count is:', currentCount);223}224```225226### Store Patterns227228Common patterns for using stores effectively in Svelte applications.229230**Custom Store Pattern:**231232```javascript233import { writable } from "svelte/store";234235function createCounter() {236const { subscribe, set, update } = writable(0);237238return {239subscribe,240increment: () => update(n => n + 1),241decrement: () => update(n => n - 1),242reset: () => set(0)243};244}245246export const counter = createCounter();247```248249**Store with Validation:**250251```javascript252import { writable } from "svelte/store";253254function createValidatedStore(initialValue, validator) {255const { subscribe, set } = writable(initialValue);256257return {258subscribe,259set: (value) => {260if (validator(value)) {261set(value);262} else {263throw new Error('Invalid value');264}265}266};267}268269const email = createValidatedStore('', (value) => {270return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);271});272```273274**Local Storage Store:**275276```javascript277import { writable } from "svelte/store";278279function createLocalStorageStore(key, initialValue) {280const storedValue = localStorage.getItem(key);281const store = writable(storedValue ? JSON.parse(storedValue) : initialValue);282283return {284subscribe: store.subscribe,285set: (value) => {286localStorage.setItem(key, JSON.stringify(value));287store.set(value);288},289update: (callback) => {290store.update((value) => {291const newValue = callback(value);292localStorage.setItem(key, JSON.stringify(newValue));293return newValue;294});295}296};297}298299const settings = createLocalStorageStore('app-settings', { theme: 'light' });300```