fix(use-theme): add SSR safety guards for window access
setTheme, toggleTheme, and storage event listener now check typeof window before accessing localStorage/addEventListener. Prevents crashes in Next.js server components.
This commit is contained in:
parent
6f4957d821
commit
e194365711
@ -49,6 +49,8 @@ export function useTheme(options?: UseThemeOptions): UseThemeReturn {
|
|||||||
|
|
||||||
// Sync across tabs via storage event
|
// Sync across tabs via storage event
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
|
||||||
function handleStorage(event: StorageEvent) {
|
function handleStorage(event: StorageEvent) {
|
||||||
if (event.key !== storageKey) {
|
if (event.key !== storageKey) {
|
||||||
return;
|
return;
|
||||||
@ -65,7 +67,9 @@ export function useTheme(options?: UseThemeOptions): UseThemeReturn {
|
|||||||
const setTheme = useCallback(
|
const setTheme = useCallback(
|
||||||
(t: Theme) => {
|
(t: Theme) => {
|
||||||
setThemeState(t);
|
setThemeState(t);
|
||||||
window.localStorage.setItem(storageKey, t);
|
if (typeof window !== 'undefined') {
|
||||||
|
window.localStorage.setItem(storageKey, t);
|
||||||
|
}
|
||||||
},
|
},
|
||||||
[storageKey]
|
[storageKey]
|
||||||
);
|
);
|
||||||
@ -73,7 +77,9 @@ export function useTheme(options?: UseThemeOptions): UseThemeReturn {
|
|||||||
const toggleTheme = useCallback(() => {
|
const toggleTheme = useCallback(() => {
|
||||||
setThemeState(prev => {
|
setThemeState(prev => {
|
||||||
const next: Theme = prev === 'dark' ? 'light' : 'dark';
|
const next: Theme = prev === 'dark' ? 'light' : 'dark';
|
||||||
window.localStorage.setItem(storageKey, next);
|
if (typeof window !== 'undefined') {
|
||||||
|
window.localStorage.setItem(storageKey, next);
|
||||||
|
}
|
||||||
applyTheme(next, attribute);
|
applyTheme(next, attribute);
|
||||||
return next;
|
return next;
|
||||||
});
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user