What if your app could update itself instantly without you writing extra update code?
Why Store contract (subscribe method) in Svelte? - Purpose & Use Cases
Imagine you have a web page with multiple parts showing the same data, like a shopping cart total and a list of items. Every time the data changes, you have to find all those parts and update them manually.
Manually updating each part is slow and easy to forget. If you miss one place, the page shows wrong info. It's like trying to update every clock in a building by hand whenever the time changes.
The store contract with the subscribe method lets parts of your app listen for data changes automatically. When data updates, all listeners get notified and update themselves without extra work.
cartTotalElement.textContent = newTotal; itemListElement.innerHTML = newItemsHtml;
const unsubscribe = cartStore.subscribe(value => {
cartTotal = value.total;
items = value.items;
});This lets your app keep data and UI in sync effortlessly, making your code cleaner and your app more reliable.
Think of a live sports score app where multiple parts show the score, time, and player stats. Using subscribe, all parts update instantly when the score changes.
Manual updates are slow and error-prone.
Subscribe method automates data change notifications.
It keeps UI and data perfectly in sync.
Practice
subscribe method of a Svelte store do?Solution
Step 1: Understand the purpose of
Thesubscribesubscribemethod allows you to listen to changes in the store's value.Step 2: Identify what
It lets your code react immediately whenever the store value changes.subscribeenablesFinal Answer:
It lets you watch store changes and react immediately. -> Option DQuick Check:
subscribe watches changes = C [OK]
- Thinking subscribe changes the store value
- Confusing subscribe with reset or delete
- Assuming subscribe returns the store value directly
count?Solution
Step 1: Recall the store subscription syntax
The correct way is to callsubscribeas a method on the store with a callback.Step 2: Match the syntax to the options
count.subscribe(value => console.log(value)); correctly callscount.subscribewith a function to receive updates.Final Answer:
count.subscribe(value => console.log(value)); -> Option BQuick Check:
Method call subscribe with callback = A [OK]
- Assigning subscribe instead of calling it
- Using a non-existent method like onSubscribe
- Calling subscribe as a standalone function
import { writable } from 'svelte/store';
const count = writable(0);
const unsubscribe = count.subscribe(value => console.log(value));
count.set(5);
unsubscribe();
count.set(10);Solution
Step 1: Understand initial subscription behavior
When subscribing, the callback immediately receives the current value, which is 0.Step 2: Trace subsequent updates and unsubscription
After setting to 5, the callback logs 5. Thenunsubscribe()stops listening, so setting to 10 logs nothing.Final Answer:
0, 5 -> Option AQuick Check:
subscribe logs initial + updates until unsubscribe = B [OK]
- Expecting logs after unsubscribe
- Missing initial immediate callback call
- Confusing set with update method
import { writable } from 'svelte/store';
const count = writable(0);
count.subscribe(value => console.log(value));
count.unsubscribe();Solution
Step 1: Understand unsubscribe usage
Thesubscribemethod returns anunsubscribefunction to stop listening.Step 2: Identify the error in calling unsubscribe
Callingunsubscribedirectly on the store is invalid; you must call the function returned bysubscribe.Final Answer:
You cannot call unsubscribe directly on the store. -> Option CQuick Check:
unsubscribe is returned by subscribe, not a store method [OK]
- Calling unsubscribe on the store instead of returned function
- Expecting subscribe callback to return a value
- Confusing store initialization types
subscribe method to follow the store contract?Solution
Step 1: Check the subscribe method signature
The subscribe method must accept a callbackrunand call it immediately with the current value.Step 2: Verify logging and return of unsubscribe
function customStore() { let value = 0; return { subscribe(run) { console.log('subscribed'); run(value); return () => console.log('unsubscribed'); } }; } logs 'subscribed' before callingrun(value)and returns a function that logs 'unsubscribed'.Step 3: Confirm distractors are invalid
B misses callingrun(value), C lacksrunparameter, D misses returning the unsubscribe function.Final Answer:
correctly implements subscribe with logging and unsubscribe function -> Option AQuick Check:
subscribe calls run(value) and returns unsubscribe function [OK]
- Not calling run with current value
- Missing the unsubscribe function return
- Logging after calling run instead of before
Ready to prove it?
Pass the test and this pattern moves unknown
