0 day streak
javascript / intermediate
Snippet

Encapsulating Logic in Readable Stores

Readable stores are used when the data source is external and shouldn't be modified by the components using it. The second argument is a setup function that returns a cleanup function.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
import { readable } from 'svelte/store';
export const time = readable(new Date(), set => {
const interval = setInterval(() => {
set(new Date());
}, 1000);
return () => clearInterval(interval);
});
svelte
Breakdown
1
readable(new Date(), set => { ... });
The 'set' callback is used to update the store value from within the setup function.
2
return () => clearInterval(interval);
Returning a function provides an automatic cleanup when the last subscriber unsubscribes.
3
new Date()
The first argument is the initial value of the store.