fix: make useIsMobile hook and utility functions SSR-safe
- Refactor use-mobile.tsx to use getServerSnapshot for SSR - Add window guard to consoleDebug in debug.ts - Add window guard to isLocalEnvironment in track-event.ts
This commit is contained in:
parent
30d64f8249
commit
40762bc528
|
|
@ -2,20 +2,28 @@ import { useSyncExternalStore } from 'react';
|
|||
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
|
||||
function mediaQueryListener(callback: (event: MediaQueryListEvent) => void) {
|
||||
mql.addEventListener('change', callback);
|
||||
|
||||
return () => {
|
||||
mql.removeEventListener('change', callback);
|
||||
};
|
||||
function getMediaQueryList(): MediaQueryList | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
return window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
}
|
||||
|
||||
function isSmallerThanBreakpoint() {
|
||||
return mql.matches;
|
||||
function subscribe(callback: () => void) {
|
||||
const mql = getMediaQueryList();
|
||||
if (!mql) return () => {};
|
||||
|
||||
mql.addEventListener('change', callback);
|
||||
return () => mql.removeEventListener('change', callback);
|
||||
}
|
||||
|
||||
function getSnapshot() {
|
||||
const mql = getMediaQueryList();
|
||||
return mql ? mql.matches : false;
|
||||
}
|
||||
|
||||
function getServerSnapshot() {
|
||||
return false;
|
||||
}
|
||||
|
||||
export function useIsMobile() {
|
||||
return useSyncExternalStore(mediaQueryListener, isSmallerThanBreakpoint);
|
||||
return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
export function consoleDebug(...args: unknown[]): void {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const isDebugEnabled = localStorage.getItem('debug') === 'true';
|
||||
const isLocalhost = window.location.hostname === 'localhost';
|
||||
const isTestDomain = window.location.hostname.includes('.test');
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ export interface TrackEventOptions {
|
|||
}
|
||||
|
||||
function isLocalEnvironment(): boolean {
|
||||
if (typeof window === 'undefined') return true;
|
||||
const hostname = window.location.hostname;
|
||||
return hostname === 'localhost' || hostname.endsWith('.test');
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue