0
0
Svelteframework~10 mins

Readable stores in Svelte - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a readable store that starts with the value 0.

Svelte
import { readable } from 'svelte/store';

const count = readable([1], () => {});
Drag options to blanks, or click blank then click option'
A''
Bnull
Cundefined
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using null or undefined as the initial value causes unexpected behavior.
Leaving the initial value empty or as an empty string.
2fill in blank
medium

Complete the code to set up a readable store that updates every second with the current time.

Svelte
import { readable } from 'svelte/store';

const time = readable(new Date(), function start(set) {
  const interval = setInterval(() => {
    set([1]);
  }, 1000);

  return () => clearInterval(interval);
});
Drag options to blanks, or click blank then click option'
ADate.now()
Bnew Date()
CDate.toString()
DsetInterval()
Attempts:
3 left
💡 Hint
Common Mistakes
Using Date.now() returns a timestamp number, not a Date object.
Calling setInterval() inside set causes errors.
3fill in blank
hard

Fix the error in the readable store that tries to update a count every second but does not clear the interval.

Svelte
import { readable } from 'svelte/store';

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

  return () => [1];
});
Drag options to blanks, or click blank then click option'
AclearInterval(interval)
BclearTimeout(interval)
CstopInterval(interval)
DcancelInterval(interval)
Attempts:
3 left
💡 Hint
Common Mistakes
Using clearTimeout instead of clearInterval.
Not returning a cleanup function at all.
4fill in blank
hard

Fill both blanks to create a readable store that fetches data once and stops when unsubscribed.

Svelte
import { readable } from 'svelte/store';

const data = readable(null, (set) => {
  fetch('/api/data')
    .then(response => response.json())
    .then([1] => set([2]));

  return () => {};
});
Drag options to blanks, or click blank then click option'
Adata
Bresult
Cresponse
Djson
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing confusion.
Passing the wrong variable to set.
5fill in blank
hard

Fill all three blanks to create a readable store that counts seconds and stops after 10 seconds.

Svelte
import { readable } from 'svelte/store';

const timer = readable(0, (set) => {
  let count = 0;
  const interval = setInterval(() => {
    count += 1;
    set([1]);
    if (count === [2]) {
      [3](interval);
    }
  }, 1000);

  return () => clearInterval(interval);
});
Drag options to blanks, or click blank then click option'
Acount
B10
CclearInterval
DsetInterval
Attempts:
3 left
💡 Hint
Common Mistakes
Using setInterval instead of clearInterval to stop the timer.
Not updating the store with the count variable.