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
Revolutionary JavaScript framework and compiler that builds web applications without runtime overhead by compiling components at build time.
Author
tessl
Last updated

How to use

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

store-management.md docs/

1
# Store Management
2
3
Reactive state management system with readable, writable, and derived stores for application-wide state.
4
5
## Capabilities
6
7
### Writable Stores
8
9
Create stores that can be read from and written to by any part of your application.
10
11
```javascript { .api }
12
/**
13
* Creates a writable store that allows both updating and reading by subscription
14
* @param value - Initial value
15
* @param start - Optional start/stop notifier function
16
* @returns Writable store instance
17
*/
18
function writable<T>(value?: T, start?: StartStopNotifier<T>): Writable<T>;
19
20
interface Writable<T> extends Readable<T> {
21
/** Set value and inform subscribers */
22
set(this: void, value: T): void;
23
/** Update value using callback and inform subscribers */
24
update(this: void, updater: Updater<T>): void;
25
}
26
27
interface Readable<T> {
28
/** Subscribe to value changes */
29
subscribe(this: void, run: Subscriber<T>, invalidate?: Invalidator<T>): Unsubscriber;
30
}
31
32
type Subscriber<T> = (value: T) => void;
33
type Unsubscriber = () => void;
34
type Updater<T> = (value: T) => T;
35
type Invalidator<T> = (value?: T) => void;
36
```
37
38
**Usage Examples:**
39
40
```javascript
41
import { writable } from "svelte/store";
42
43
// Basic writable store
44
const count = writable(0);
45
46
// Subscribe to changes
47
const unsubscribe = count.subscribe(value => {
48
console.log('Count is now:', value);
49
});
50
51
// Update the store
52
count.set(5);
53
count.update(n => n + 1);
54
55
// Clean up subscription
56
unsubscribe();
57
58
// Store with start/stop logic
59
const websocketStore = writable(null, (set) => {
60
const socket = new WebSocket('ws://localhost:8080');
61
62
socket.onmessage = (event) => {
63
set(JSON.parse(event.data));
64
};
65
66
return () => {
67
socket.close();
68
};
69
});
70
```
71
72
### Readable Stores
73
74
Create read-only stores that can be subscribed to but not directly modified.
75
76
```javascript { .api }
77
/**
78
* Creates a readable store that allows reading by subscription
79
* @param value - Initial value
80
* @param start - Optional start/stop notifier function
81
* @returns Readable store instance
82
*/
83
function readable<T>(value?: T, start?: StartStopNotifier<T>): Readable<T>;
84
85
type StartStopNotifier<T> = (
86
set: (value: T) => void,
87
update: (fn: Updater<T>) => void
88
) => void | (() => void);
89
```
90
91
**Usage Examples:**
92
93
```javascript
94
import { readable } from "svelte/store";
95
96
// Time store that updates every second
97
const time = readable(new Date(), (set) => {
98
const interval = setInterval(() => {
99
set(new Date());
100
}, 1000);
101
102
return () => clearInterval(interval);
103
});
104
105
// Mouse position store
106
const mousePosition = readable({ x: 0, y: 0 }, (set) => {
107
const handleMouseMove = (event) => {
108
set({ x: event.clientX, y: event.clientY });
109
};
110
111
document.addEventListener('mousemove', handleMouseMove);
112
113
return () => {
114
document.removeEventListener('mousemove', handleMouseMove);
115
};
116
});
117
```
118
119
### Derived Stores
120
121
Create stores whose values are computed from other stores.
122
123
```javascript { .api }
124
/**
125
* Creates a derived store by synchronizing one or more readable stores
126
* @param stores - Input stores (single store or array)
127
* @param fn - Function to compute derived value
128
* @param initial_value - Optional initial value
129
* @returns Readable store with derived value
130
*/
131
function derived<S extends Stores, T>(
132
stores: S,
133
fn: (values: StoresValues<S>, set: (value: T) => void, update: (fn: Updater<T>) => void) => Unsubscriber | void,
134
initial_value?: T
135
): Readable<T>;
136
137
function derived<S extends Stores, T>(
138
stores: S,
139
fn: (values: StoresValues<S>) => T,
140
initial_value?: T
141
): Readable<T>;
142
143
type Stores = Readable<any> | [Readable<any>, ...Array<Readable<any>>] | Array<Readable<any>>;
144
type StoresValues<T> = T extends Readable<infer U> ? U : { [K in keyof T]: T[K] extends Readable<infer U> ? U : never };
145
```
146
147
**Usage Examples:**
148
149
```javascript
150
import { writable, derived } from "svelte/store";
151
152
const firstName = writable('John');
153
const lastName = writable('Doe');
154
155
// Simple derived store
156
const fullName = derived(
157
[firstName, lastName],
158
([first, last]) => `${first} ${last}`
159
);
160
161
// Derived store with initial value
162
const greeting = derived(
163
fullName,
164
($fullName) => `Hello, ${$fullName}!`,
165
'Hello, World!'
166
);
167
168
// Async derived store with set callback
169
const userProfile = derived(
170
userId,
171
($userId, set) => {
172
if (!$userId) {
173
set(null);
174
return;
175
}
176
177
fetch(`/api/users/${$userId}`)
178
.then(res => res.json())
179
.then(set);
180
},
181
null
182
);
183
```
184
185
### Store Utilities
186
187
Utility functions for working with stores.
188
189
```javascript { .api }
190
/**
191
* Makes a store readonly
192
* @param store - Store to make readonly
193
* @returns Readonly version of the store
194
*/
195
function readonly<T>(store: Readable<T>): Readable<T>;
196
197
/**
198
* Gets the current value from a store by subscribing and immediately unsubscribing
199
* @param store - Store to get value from
200
* @returns Current store value
201
*/
202
function get<T>(store: Readable<T>): T;
203
```
204
205
**Usage Examples:**
206
207
```javascript
208
import { writable, readonly, get } from "svelte/store";
209
210
const internalStore = writable(42);
211
212
// Create readonly version for external use
213
export const publicStore = readonly(internalStore);
214
215
// Get current value without subscribing
216
const currentValue = get(internalStore);
217
console.log('Current value:', currentValue);
218
219
// Useful in event handlers
220
function handleClick() {
221
const currentCount = get(count);
222
console.log('Button clicked, count is:', currentCount);
223
}
224
```
225
226
### Store Patterns
227
228
Common patterns for using stores effectively in Svelte applications.
229
230
**Custom Store Pattern:**
231
232
```javascript
233
import { writable } from "svelte/store";
234
235
function createCounter() {
236
const { subscribe, set, update } = writable(0);
237
238
return {
239
subscribe,
240
increment: () => update(n => n + 1),
241
decrement: () => update(n => n - 1),
242
reset: () => set(0)
243
};
244
}
245
246
export const counter = createCounter();
247
```
248
249
**Store with Validation:**
250
251
```javascript
252
import { writable } from "svelte/store";
253
254
function createValidatedStore(initialValue, validator) {
255
const { subscribe, set } = writable(initialValue);
256
257
return {
258
subscribe,
259
set: (value) => {
260
if (validator(value)) {
261
set(value);
262
} else {
263
throw new Error('Invalid value');
264
}
265
}
266
};
267
}
268
269
const email = createValidatedStore('', (value) => {
270
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
271
});
272
```
273
274
**Local Storage Store:**
275
276
```javascript
277
import { writable } from "svelte/store";
278
279
function createLocalStorageStore(key, initialValue) {
280
const storedValue = localStorage.getItem(key);
281
const store = writable(storedValue ? JSON.parse(storedValue) : initialValue);
282
283
return {
284
subscribe: store.subscribe,
285
set: (value) => {
286
localStorage.setItem(key, JSON.stringify(value));
287
store.set(value);
288
},
289
update: (callback) => {
290
store.update((value) => {
291
const newValue = callback(value);
292
localStorage.setItem(key, JSON.stringify(newValue));
293
return newValue;
294
});
295
}
296
};
297
}
298
299
const settings = createLocalStorageStore('app-settings', { theme: 'light' });
300
```