Skip to content

Commit 3ffcf49

Browse files
committed
Add nanostore atom, for being able to subscribing to its change
1 parent ea84581 commit 3ffcf49

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/lib/theme.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
type Theme = "light" | "dark";
1+
export type Theme = "light" | "dark";
22

3-
function getCurrentTheme(): Theme {
3+
export function getCurrentTheme(): Theme {
44
return (document.documentElement.dataset.theme ?? "light") as Theme;
55
}
66

@@ -20,4 +20,8 @@ export function observeThemeChange(cb: (theme: Theme) => void) {
2020

2121
// Initial value
2222
cb(getCurrentTheme());
23+
24+
return () => {
25+
observer.disconnect();
26+
};
2327
}

src/stores/theme.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { atom, onMount } from "nanostores";
2+
import { getCurrentTheme, observeThemeChange } from "~/lib/theme";
3+
4+
export const $theme = atom(getCurrentTheme());
5+
6+
onMount($theme, () => {
7+
return observeThemeChange((theme) => {
8+
$theme.set(theme);
9+
});
10+
});

0 commit comments

Comments
 (0)