Skip to content

Commit be2129f

Browse files
committed
fix(ui): 🐛 fix bug of can't get localstorage in server process
1 parent f8bb0cf commit be2129f

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

composables/darkmode/index.ts

+21-15
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,31 @@
11
const themes = ['system', 'light', 'dark'] as const
22
export type Themes = typeof themes[number]
33

4-
export const themePreference = useLocalStorage<Themes>('theme_preference', 'system', {
5-
listenToStorageChanges: true,
6-
serializer: {
7-
read(raw): Themes {
8-
return themes.includes(raw as any) ? (raw as Themes) : 'system'
9-
},
10-
write(value): string {
11-
return value
12-
},
13-
},
14-
})
15-
16-
export const isDark = computed(() =>
17-
themePreference.value === 'system' ? usePreferredDark().value : themePreference.value === 'dark',
18-
)
4+
export const themePreference = ref<Themes>('system')
5+
export const isDark = ref(false)
196

207
export function applyTheme() {
218
// Attention: only client has 'document' object
229
if (process.client) {
10+
const storedPreference = useLocalStorage<Themes>('theme_preference', 'system', {
11+
listenToStorageChanges: true,
12+
serializer: {
13+
read(raw): Themes {
14+
return themes.includes(raw as any) ? (raw as Themes) : 'system'
15+
},
16+
write(value): string {
17+
return value
18+
},
19+
},
20+
})
21+
themePreference.value = storedPreference.value
22+
23+
watchEffect(() => {
24+
isDark.value = computed(() =>
25+
themePreference.value === 'system' ? usePreferredDark().value : themePreference.value === 'dark',
26+
).value
27+
})
28+
2329
const html = document.documentElement
2430
const metaTag = document.querySelector('meta[name="theme-color"]')
2531
watchEffect(() => {

0 commit comments

Comments
 (0)