Complete the code to subscribe to a Svelte store and log its value.
myStore.[1](value => console.log(value));The subscribe method is used to listen to changes in a Svelte store.
Complete the code to unsubscribe from a Svelte store subscription.
const unsubscribe = myStore.subscribe(() => {});
unsubscribe[1];The unsubscribe function returned by subscribe must be called as a function to stop listening.
Fix the error in the subscribe callback parameter to correctly receive the store value.
myStore.subscribe([1] => { console.log([1]); });
The callback receives the current store value as its first argument, commonly named value.
Fill both blanks to create a custom store with a subscribe method that calls the subscriber immediately.
function createStore() {
return {
subscribe: function([1]) {
[2]('hello');
return () => {};
}
};
}The subscribe method takes a subscriber function and calls it immediately with the current value.
Fill all three blanks to implement a store with subscribe, set, and update methods following the Svelte store contract.
function createCounter() {
let count = 0;
const subscribers = new Set();
function notify() {
subscribers.forEach([1] => [2](count));
}
return {
subscribe([3]) {
subscribers.add([3]);
[3](count);
return () => subscribers.delete([3]);
},
set(value) {
count = value;
notify();
},
update(fn) {
count = fn(count);
notify();
}
};
}The subscribe method adds a subscriber function to the set and calls it immediately with the current value. The notify function calls each subscriber with the updated count.