Spec RegistrySpec Registry

Help your agents use open-source better. Learn more.

Find usage specs for your project’s dependencies

>

npm-svelte

Describes: npmnpm/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

How to use

npx @tessl/cli registry install tessl/npm-svelte@5.38.0

stores.md docs/

1
# Store System
2
3
Svelte'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.
4
5
## Capabilities
6
7
### writable
8
9
Creates a store with both read and write capabilities. Subscribers are notified when the value changes.
10
11
```typescript { .api }
12
/**
13
* Create a writable store that allows both updating and reading by subscription
14
* @param value - Initial value (optional)
15
* @param start - Function called when first subscriber subscribes
16
* @returns Writable store instance
17
*/
18
function writable<T>(value?: T, start?: StartStopNotifier<T>): Writable<T>;
19
```
20
21
**Usage Examples:**
22
23
```typescript
24
import { writable } from "svelte/store";
25
26
// Basic writable store
27
const count = writable(0);
28
29
// Store with initial value
30
const user = writable({ name: "Alice", age: 30 });
31
32
// Store with start/stop logic
33
const time = writable(new Date(), (set) => {
34
const interval = setInterval(() => {
35
set(new Date());
36
}, 1000);
37
38
// Cleanup function called when last subscriber unsubscribes
39
return () => clearInterval(interval);
40
});
41
42
// Using stores in components
43
count.subscribe(value => {
44
console.log("Count:", value);
45
});
46
47
// Update store values
48
count.set(5);
49
count.update(n => n + 1);
50
51
// Auto-subscribe in Svelte components with $
52
// let currentCount = $count; // Automatically subscribes
53
```
54
55
### readable
56
57
Creates a read-only store. The value can only be set from within the store's start function.
58
59
```typescript { .api }
60
/**
61
* Creates a readable store that allows reading by subscription
62
* @param value - Initial value (optional)
63
* @param start - Function called when first subscriber subscribes
64
* @returns Readable store instance
65
*/
66
function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T>;
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
import { readable } from "svelte/store";
73
74
// Static readable store
75
const appName = readable("My App");
76
77
// Dynamic readable store
78
const mousePosition = readable({ x: 0, y: 0 }, (set) => {
79
const handleMouseMove = (event) => {
80
set({ x: event.clientX, y: event.clientY });
81
};
82
83
document.addEventListener("mousemove", handleMouseMove);
84
85
return () => {
86
document.removeEventListener("mousemove", handleMouseMove);
87
};
88
});
89
90
// WebSocket store example
91
const websocketStore = readable(null, (set) => {
92
const ws = new WebSocket("ws://localhost:8080");
93
94
ws.onmessage = (event) => {
95
set(JSON.parse(event.data));
96
};
97
98
return () => {
99
ws.close();
100
};
101
});
102
```
103
104
### derived
105
106
Creates a store whose value is computed from one or more other stores. Updates automatically when dependencies change.
107
108
```typescript { .api }
109
/**
110
* Derived store that computes its value from other stores
111
* @param stores - Single store or array of stores to derive from
112
* @param fn - Function that computes the derived value
113
* @param initial_value - Initial value before first computation
114
* @returns Readable derived store
115
*/
116
function derived<S extends Stores, T>(
117
stores: S,
118
fn: (values: StoresValues<S>) => T,
119
initial_value?: T
120
): Readable<T>;
121
122
/**
123
* Derived store with async computation
124
* @param stores - Single store or array of stores to derive from
125
* @param fn - Function that computes value with set callback
126
* @param initial_value - Initial value before first computation
127
* @returns Readable derived store
128
*/
129
function derived<S extends Stores, T>(
130
stores: S,
131
fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void,
132
initial_value?: T
133
): Readable<T>;
134
```
135
136
**Usage Examples:**
137
138
```typescript
139
import { writable, derived } from "svelte/store";
140
141
const firstName = writable("John");
142
const lastName = writable("Doe");
143
144
// Simple derived store
145
const fullName = derived(
146
[firstName, lastName],
147
([first, last]) => `${first} ${last}`
148
);
149
150
// Single store derivation
151
const doubled = derived(count, n => n * 2);
152
153
// Derived with initial value
154
const greeting = derived(
155
fullName,
156
name => `Hello, ${name}!`,
157
"Hello, Guest!"
158
);
159
160
// Async derived store
161
const userProfile = derived(
162
userId,
163
(id, set) => {
164
if (!id) {
165
set(null);
166
return;
167
}
168
169
const controller = new AbortController();
170
171
fetch(`/api/users/${id}`, { signal: controller.signal })
172
.then(r => r.json())
173
.then(profile => set(profile))
174
.catch(err => {
175
if (!controller.signal.aborted) {
176
console.error("Failed to fetch user:", err);
177
set(null);
178
}
179
});
180
181
return () => controller.abort();
182
},
183
null
184
);
185
186
// Complex derived computation
187
const statistics = derived(
188
[users, posts, comments],
189
([userList, postList, commentList]) => ({
190
totalUsers: userList.length,
191
totalPosts: postList.length,
192
totalComments: commentList.length,
193
avgCommentsPerPost: commentList.length / postList.length || 0
194
})
195
);
196
```
197
198
### get
199
200
Synchronously retrieves the current value from a store without subscribing.
201
202
```typescript { .api }
203
/**
204
* Get the current value from a store by subscribing and immediately unsubscribing
205
* @param store - Store to get value from
206
* @returns Current store value
207
*/
208
function get<T>(store: Readable<T>): T;
209
```
210
211
**Usage Examples:**
212
213
```typescript
214
import { writable, get } from "svelte/store";
215
216
const count = writable(42);
217
218
// Get current value without subscribing
219
const currentCount = get(count);
220
console.log(currentCount); // 42
221
222
// Useful for one-off operations
223
function logCurrentState() {
224
console.log({
225
count: get(count),
226
user: get(user),
227
settings: get(settings)
228
});
229
}
230
231
// In event handlers where you need current value
232
function handleClick() {
233
const current = get(count);
234
if (current > 10) {
235
// Do something
236
}
237
}
238
```
239
240
### readonly
241
242
Creates a read-only version of a writable store, preventing external modifications.
243
244
```typescript { .api }
245
/**
246
* Takes a store and returns a new one derived from the old one that is readable
247
* @param store - Store to make readonly
248
* @returns Readonly version of the store
249
*/
250
function readonly<T>(store: Readable<T>): Readable<T>;
251
```
252
253
**Usage Examples:**
254
255
```typescript
256
import { writable, readonly } from "svelte/store";
257
258
// Internal writable store
259
const _settings = writable({
260
theme: "light",
261
language: "en"
262
});
263
264
// Public readonly interface
265
export const settings = readonly(_settings);
266
267
// Internal functions can still modify
268
export function updateTheme(theme) {
269
_settings.update(s => ({ ...s, theme }));
270
}
271
272
export function updateLanguage(language) {
273
_settings.update(s => ({ ...s, language }));
274
}
275
276
// External consumers can only read
277
// settings.set(...) // This would cause a TypeScript error
278
```
279
280
### Store Conversion Utilities
281
282
Convert between Svelte 5 runes and stores for interoperability.
283
284
```typescript { .api }
285
/**
286
* Create a store from a function that returns state
287
* @param get - Function that returns current value
288
* @param set - Optional function to update value (makes it writable)
289
* @returns Store (readable or writable based on parameters)
290
*/
291
function toStore<V>(get: () => V, set: (v: V) => void): Writable<V>;
292
function toStore<V>(get: () => V): Readable<V>;
293
294
/**
295
* Convert a store to an object with a reactive current property
296
* @param store - Store to convert
297
* @returns Object with current property
298
*/
299
function fromStore<V>(store: Writable<V>): { current: V };
300
function fromStore<V>(store: Readable<V>): { readonly current: V };
301
```
302
303
**Usage Examples:**
304
305
```typescript
306
import { toStore, fromStore } from "svelte/store";
307
308
// Convert rune state to store
309
let count = $state(0);
310
const countStore = toStore(
311
() => count,
312
(value) => count = value
313
);
314
315
// Convert store to rune-like object
316
const settings = writable({ theme: "light" });
317
const settingsRune = fromStore(settings);
318
319
// Use like rune state
320
$effect(() => {
321
console.log("Theme:", settingsRune.current.theme);
322
});
323
324
// Update through original store
325
settings.update(s => ({ ...s, theme: "dark" }));
326
```
327
328
## Types
329
330
```typescript { .api }
331
interface Readable<T> {
332
/**
333
* Subscribe to store changes
334
* @param run - Function called with current value and on changes
335
* @param invalidate - Optional cleanup function
336
* @returns Unsubscribe function
337
*/
338
subscribe(run: Subscriber<T>, invalidate?: () => void): Unsubscriber;
339
}
340
341
interface Writable<T> extends Readable<T> {
342
/**
343
* Set the store value and notify subscribers
344
* @param value - New value to set
345
*/
346
set(value: T): void;
347
348
/**
349
* Update the store value using a function and notify subscribers
350
* @param updater - Function that receives current value and returns new value
351
*/
352
update(updater: Updater<T>): void;
353
}
354
355
type Subscriber<T> = (value: T) => void;
356
type Unsubscriber = () => void;
357
type Updater<T> = (value: T) => T;
358
359
type StartStopNotifier<T> = (
360
set: (value: T) => void,
361
update: (fn: Updater<T>) => void
362
) => void | (() => void);
363
364
type Stores = Readable<any> | [Readable<any>, ...Array<Readable<any>>] | Array<Readable<any>>;
365
366
type StoresValues<T> = T extends Readable<infer U>
367
? U
368
: { [K in keyof T]: T[K] extends Readable<infer U> ? U : never };
369
```
370
371
## Best Practices
372
373
1. **Use stores for global state**: Perfect for user authentication, app settings, shopping carts
374
2. **Prefer derived over manual subscriptions**: Let Svelte handle the reactivity
375
3. **Clean up subscriptions**: Always call the unsubscriber function to prevent memory leaks
376
4. **Use readonly for public APIs**: Expose readonly stores when you want to control mutations
377
5. **Consider custom stores**: Create specialized stores with domain-specific methods
378
6. **Lazy loading**: Use start/stop notifiers to manage expensive resources like WebSocket connections