Настройка State Management (Svelte Store) для Svelte-додатку
Svelte сторі — найпростіший state management: реактивні змінні, які автоматично запускають оновлення. Ніякого boilerplate, ніякого контексту, тільки підписки.
Ідеально для малих та середніх Svelte додатків.
Що входить у роботу
Створення writable сторів, derived сторів, кастомних сторів, інтеграція зі Svelte компонентами.
Writable сторі
import { writable, derived, readable } from 'svelte/store'
export const count = writable(0)
export const doubled = derived(count, c => c * 2)
export const cartItems = writable<CartItem[]>([])
export const cartTotal = derived(cartItems, items =>
items.reduce((sum, i) => sum + i.price * i.qty, 0)
)
Використання в компонентах:
<script>
import { count, doubled, cartItems, cartTotal } from './stores.ts'
</script>
<button on:click={() => count.update(n => n + 1)}>
Лічильник: {$count} (подвоєно: {$doubled})
</button>
<div>Товарів: {$cartItems.length}, Всього: ${$cartTotal}</div>
Кастомні сторі
function createCart() {
const { subscribe, set, update } = writable<CartItem[]>([])
return {
subscribe,
addItem: (item: CartItem) => update(items => [...items, item]),
removeItem: (id: string) => update(items => items.filter(i => i.id !== id)),
clear: () => set([]),
}
}
export const cart = createCart()
Терміни
Базова настройка сторів — 30 хвилин. Кілька derived сторів — 1 година. Складні кастомні сторі — 2–3 години.







