Bird
Raised Fist0
Svelteframework~10 mins

Readable stores in Svelte - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Readable stores
Create readable store with initial value
↓
Subscribe function called
↓
Subscriber receives current value
↓
Store updates internally (optional)
↓
Subscribers notified with new value
↓
Unsubscribe when no longer needed
↓
End
Readable stores provide values that can be subscribed to but not directly changed by subscribers. Updates come from inside the store.
Execution Sample
Svelte
import { readable } from 'svelte/store';

const time = readable(new Date(), set => {
  const interval = setInterval(() => set(new Date()), 1000);
  return () => clearInterval(interval);
});
Creates a readable store that updates the current time every second.
Execution Table
StepActionStore ValueSubscriber CalledNotes
1Create readable store with initial valueCurrent Date at creationNoStore initialized with current time
2Subscribe to storeCurrent Date at creationYesSubscriber receives initial value immediately
31 second passes, interval triggers set()New Date +1sYesSubscriber notified with updated time
4Another second passes, interval triggers set()New Date +2sYesSubscriber notified again
5Unsubscribe calledLast Date valueNoInterval cleared, no more updates
6No more updatesLast Date valueNoStore stops updating after unsubscribe
💡 Unsubscribe clears interval, stopping updates and subscriber calls
Variable Tracker
VariableStartAfter 1After 2After Unsubscribe
store valueDate at creationDate +1sDate +2sDate +2s
subscriber calledNoYesYesNo
interval activeYesYesYesNo
Key Moments - 2 Insights
Why can't subscribers directly change the value of a readable store?
Readable stores only allow internal updates via the set function inside the store. Subscribers get notified but cannot set values themselves, as shown in steps 2 and 3 of the execution_table.
What happens when you unsubscribe from a readable store?
Unsubscribing calls the cleanup function that stops internal updates (like clearing intervals). This is shown in step 5 where the interval is cleared and no further subscriber calls happen.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the store value at step 3?
AInitial Date at creation
BNew Date +1s
CNew Date +2s
DNo value
💡 Hint
Check the 'Store Value' column at step 3 in the execution_table
At which step does the subscriber stop receiving updates?
AStep 5
BStep 3
CStep 2
DStep 6
💡 Hint
Look at the 'Subscriber Called' column and the notes about unsubscribe in the execution_table
If the cleanup function did not clear the interval, what would happen?
ASubscriber would never get updates
BStore value would never change
CSubscriber would keep getting updates even after unsubscribe
DStore would throw an error
💡 Hint
Refer to the 'interval active' variable in variable_tracker and step 5 in execution_table
Concept Snapshot
Readable stores in Svelte:
- Created with readable(initialValue, startFunction)
- Subscribers get current value immediately
- Only internal code can update value via set()
- Cleanup function stops updates on unsubscribe
- Subscribers cannot directly change store value
Full Transcript
Readable stores in Svelte provide a way to share data that can be read and subscribed to but not directly changed by subscribers. When you create a readable store, you give it an initial value and a function that can update the value internally, like a timer. Subscribers get the current value right away and get notified whenever the store updates. When they unsubscribe, the store runs a cleanup function to stop updates, such as clearing an interval. This keeps the data flow controlled and predictable.

Practice

(1/5)
1. What is the main purpose of a readable store in Svelte?
easy
A. To create a store that holds static, non-reactive data
B. To allow components to write and update the store value directly
C. To provide reactive data that cannot be changed from outside the store
D. To replace writable stores for all state management

Solution

  1. Step 1: Understand readable store purpose

    A readable store provides reactive data but restricts external modifications.
  2. Step 2: Compare with writable stores

    Writable stores allow external updates, readable stores do not.
  3. Final Answer:

    To provide reactive data that cannot be changed from outside the store -> Option C
  4. Quick Check:

    Readable store = read-only reactive data [OK]
Hint: Readable stores are read-only from outside [OK]
Common Mistakes:
  • Confusing readable with writable stores
  • Thinking readable stores allow external updates
  • Assuming readable stores hold static data only
2. Which of the following is the correct way to create a readable store in Svelte that updates the current time every second?
easy
A. import { readable } from 'svelte/store'; const time = readable(new Date(), set => { const interval = setInterval(() => set(new Date()), 1000); return () => clearInterval(interval); });
B. import { writable } from 'svelte/store'; const time = writable(new Date());
C. import { readable } from 'svelte/store'; const time = readable(new Date());
D. import { readable } from 'svelte/store'; const time = readable(() => new Date());

Solution

  1. Step 1: Recall readable store syntax

    Readable stores take an initial value and a start function that sets updates and cleanup.
  2. Step 2: Analyze options

    import { readable } from 'svelte/store'; const time = readable(new Date(), set => { const interval = setInterval(() => set(new Date()), 1000); return () => clearInterval(interval); }); correctly uses readable with a start function that updates time every second and cleans up.
  3. Final Answer:

    import { readable } from 'svelte/store'; const time = readable(new Date(), set => { const interval = setInterval(() => set(new Date()), 1000); return () => clearInterval(interval); }); -> Option A
  4. Quick Check:

    Readable store needs start function for updates [OK]
Hint: Readable stores need a start function for dynamic updates [OK]
Common Mistakes:
  • Omitting the start function for dynamic data
  • Using writable instead of readable
  • Passing a function without calling set inside
3. Given this readable store code, what will be logged to the console after 3 seconds?
import { readable } from 'svelte/store';

const count = readable(0, set => {
  let n = 0;
  const interval = setInterval(() => {
    n += 1;
    set(n);
  }, 1000);
  return () => clearInterval(interval);
});

count.subscribe(value => console.log(value));
medium
A. Only 0
B. 1, 2, 3
C. 0, 1, 2
D. 0, 1, 2, 3

Solution

  1. Step 1: Understand initial value and updates

    The readable store starts at 0 and increments n every second, calling set(n).
  2. Step 2: Trace values over 3 seconds

    At start: 0 logged immediately. After 1s: 1, after 2s: 2, after 3s: 3 logged.
  3. Final Answer:

    0, 1, 2, 3 -> Option D
  4. Quick Check:

    Initial + increments each second = 0,1,2,3 [OK]
Hint: Readable emits initial value immediately on subscribe [OK]
Common Mistakes:
  • Ignoring initial value emission
  • Counting only increments without initial
  • Assuming subscription logs only after first interval
4. What is wrong with this readable store code?
import { readable } from 'svelte/store';

const data = readable(0, set => {
  const interval = setInterval(() => {
    set(Date.now());
  }, 1000);
  // Missing cleanup function
});
medium
A. The store is missing an initial value
B. The start function does not return a cleanup function
C. You cannot use setInterval inside a readable store
D. The set function should not be called inside the start function

Solution

  1. Step 1: Check readable store start function requirements

    The start function must return a cleanup function or undefined for cleanup.
  2. Step 2: Analyze given code

    The code creates an interval that calls set every second but does not return any cleanup function.
  3. Final Answer:

    The start function does not return a cleanup function -> Option B
  4. Quick Check:

    Start function must return cleanup or undefined [OK]
Hint: Always return cleanup function or undefined in readable start [OK]
Common Mistakes:
  • Ignoring cleanup function requirement
  • Thinking setInterval is disallowed in stores
  • Believing set cannot be called inside start
5. You want to create a readable store that emits the current window width and updates on resize. Which code snippet correctly implements this behavior?
hard
A. import { readable } from 'svelte/store'; const width = readable(window.innerWidth, set => { const onResize = () => set(window.innerWidth); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); });
B. import { writable } from 'svelte/store'; const width = writable(window.innerWidth); window.addEventListener('resize', () => width.set(window.innerWidth));
C. import { readable } from 'svelte/store'; const width = readable(() => window.innerWidth);
D. import { readable } from 'svelte/store'; const width = readable(window.innerWidth); window.addEventListener('resize', () => width.set(window.innerWidth));

Solution

  1. Step 1: Understand readable store with event listener

    Readable stores need a start function to set updates and cleanup listeners.
  2. Step 2: Check options for correct event handling and cleanup

    import { readable } from 'svelte/store'; const width = readable(window.innerWidth, set => { const onResize = () => set(window.innerWidth); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }); adds resize listener, calls set on resize, and removes listener on cleanup.
  3. Final Answer:

    import { readable } from 'svelte/store'; const width = readable(window.innerWidth, set => { const onResize = () => set(window.innerWidth); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }); -> Option A
  4. Quick Check:

    Readable with event listener and cleanup = import { readable } from 'svelte/store'; const width = readable(window.innerWidth, set => { const onResize = () => set(window.innerWidth); window.addEventListener('resize', onResize); return () => window.removeEventListener('resize', onResize); }); [OK]
Hint: Use readable with start function adding/removing event listeners [OK]
Common Mistakes:
  • Using writable store when read-only is needed
  • Not removing event listeners on cleanup
  • Passing function instead of initial value to readable
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard