What if your app could handle all the boring updates for you, perfectly every time?
Why Custom store logic in Svelte? - Purpose & Use Cases
Imagine you have a shopping cart on a website and you want to update the total price every time someone adds or removes an item. Doing this by hand means you must watch every change and update the total yourself.
Manually tracking changes is tiring and easy to mess up. You might forget to update the total or update it too late, causing wrong prices to show. It's like trying to keep score in a game without a scoreboard.
Custom store logic in Svelte lets you create a smart container that watches changes and updates the total automatically. You write the rules once, and the store handles the rest, keeping your app neat and reliable.
let total = 0; let items = []; function addItem(price) { items.push(price); total = items.reduce((a, b) => a + b, 0); }
import { writable, derived } from 'svelte/store'; function createCart() { const store = writable([]); const { subscribe, update } = store; return { subscribe, addItem: (price) => update(items => [...items, price]), total: derived(store, $items => $items.reduce((a, b) => a + b, 0)) }; }
It makes your app smarter and easier to maintain by automatically managing data changes and updates behind the scenes.
Think of a music playlist app that updates the total playtime as you add or remove songs without you needing to recalculate it every time.
Manual updates are slow and error-prone.
Custom store logic automates data tracking and updates.
This leads to cleaner, more reliable apps.
Practice
Solution
Step 1: Understand what a custom store does
A custom store extends the basic writable store by adding your own methods to control data updates and sharing.Step 2: Compare options with this understanding
Only "To add custom methods and control how data updates and shares" correctly describes this purpose. The other options misunderstand the role of custom stores: disabling reactivity, replacing the built-in writable store completely, or server-side only.Final Answer:
To add custom methods and control how data updates and shares -> Option BQuick Check:
Custom store purpose = Add custom methods [OK]
- Thinking custom stores replace writable stores entirely
- Believing custom stores disable reactivity
- Assuming custom stores only run on the server
Solution
Step 1: Check import and store creation
import { writable } from 'svelte/store'; function createStore() { const { subscribe, update } = writable(0); return { subscribe, increment: () => update(n => n + 1) }; } correctly importswritableand usesupdateto change the value.Step 2: Verify method usage
import { writable } from 'svelte/store'; function createStore() { const { subscribe, set } = writable(0); return { subscribe, increment: () => set(n => n + 1) }; } incorrectly usessetwith a function argument, which is invalid. import { readable } from 'svelte/store'; function createStore() { const { subscribe } = readable(0); return { subscribe, increment: () => {} }; } usesreadablewhich is read-only. import { store } from 'svelte/store'; function createStore() { return { subscribe: () => {}, increment: () => {} }; } imports a non-existentstore.Final Answer:
import { writable } from 'svelte/store'; function createStore() { const { subscribe, update } = writable(0); return { subscribe, increment: () => update(n => n + 1) }; } -> Option AQuick Check:
Correct syntax uses writable and update() [OK]
- Using set() with a function argument
- Using readable store when write access is needed
- Importing non-existent store types
counter.increment() twice?import { writable } from 'svelte/store';
function createCounter() {
const { subscribe, update } = writable(0);
return {
subscribe,
increment: () => update(n => n + 1)
};
}
const counter = createCounter();
counter.subscribe(value => console.log(value));
counter.increment();
counter.increment();Solution
Step 1: Understand subscription behavior
Subscribing logs the current value immediately, so 0 is logged first.Step 2: Trace increments and logs
Each increment increases the value by 1 and triggers the subscriber, logging 1 then 2.Final Answer:
0, 1, 2 -> Option AQuick Check:
Subscription logs initial and updates [OK]
- Ignoring initial subscription log
- Assuming increments log only final value
- Confusing update with set behavior
import { writable } from 'svelte/store';
function createTimer() {
const { subscribe, set } = writable(0);
let interval = null;
return {
subscribe,
start: () => {
interval = setInterval(() => set(n + 1), 1000);
},
stop: () => clearInterval(interval)
};
}Solution
Step 1: Check the setInterval callback
The callback usesset(n + 1)butnis not defined anywhere in scope.Step 2: Understand correct usage
To increment the value,updateshould be used or the current value tracked. Usingsetwith undefinedncauses an error.Final Answer:
Usingset(n + 1)without definingn-> Option CQuick Check:
Undefined variable in set() causes error [OK]
- Using set() with undefined variable
- Forgetting to clear intervals
- Confusing set and update methods
Solution
Step 1: Check method to add unique items
import { writable } from 'svelte/store'; function createList() { const { subscribe, update } = writable([]); return { subscribe, add: (item) => update(list => list.includes(item) ? list : [...list, item]) }; } usesupdateand checks if the item exists before adding, preventing duplicates.Step 2: Verify other options
import { writable } from 'svelte/store'; function createList() { const { subscribe, set } = writable([]); return { subscribe, add: (item) => set(list => list.includes(item) ? list : [...list, item]) }; } incorrectly usessetwith a function argument, which is invalid. import { readable } from 'svelte/store'; function createList() { const { subscribe } = readable([]); return { subscribe, add: (item) => {} }; } usesreadablewhich is read-only. import { writable } from 'svelte/store'; function createList() { const { subscribe, update } = writable([]); return { subscribe, add: (item) => update(list => [...list, item]) }; } adds items without checking duplicates.Final Answer:
Custom store with update() and duplicate check -> Option DQuick Check:
Use update() and check includes() for uniqueness [OK]
- Using set() with function argument
- Using readable store when write access needed
- Not checking for duplicates before adding
Ready to prove it?
Pass the test and this pattern moves unknown
