Svelte exposes a readable
function to create readable stores.
Readable accepts two arguments. The first is the default value for the store. The second a start function to keep the value up to date.
When a component subscribes to the store, it will execute the start function. We'll listen for media query changes here.
The start function must return a stop function. The stop function will be executed when no more components are subscribed to the store.
The current store value can be retrieved with $
.
import { readable } from 'svelte/store';
const mediaQueryList = window
.matchMedia('(prefers-color-scheme: dark)');
export const theme = readable(
mediaQueryList.matches ? 'dark' : 'light';,
function(set) {
function listener(query) {
set(query.matches ? 'dark' : 'light');
}
mediaQueryList.addEventListener(
'change',
listener,
);
return () => {
mediaQueryList.removeEventListener(
'change',
listener,
);
};
}
);
<script>
import { theme } from './stores.js';
</script>
<section class:dark={$theme === 'dark'}>
<!-- … -->
</section>