N-FIN-33: fix hook accessing matchMedia while undefined

This commit is contained in:
Markus Thielker 2024-03-17 01:23:21 +01:00
parent f0ee68beb2
commit 34a76cf93b
No known key found for this signature in database

View file

@ -1,16 +1,21 @@
import { useEffect, useMemo, useState } from 'react';
'use client';
import { useEffect, useState } from 'react';
export function useMediaQuery(mq: string) {
const mql = useMemo(() => matchMedia(mq), [mq]);
const [matches, setMatch] = useState(mql.matches);
const [matches, setMatch] = useState(
() => typeof window !== 'undefined' ? window.matchMedia(mq).matches : false,
);
useEffect(() => {
const listener = (e: any) => setMatch(e.matches);
mql.addEventListener('change', listener);
return () => mql.removeEventListener('change', listener);
}, [mq, mql]);
if (typeof window !== 'undefined') {
const mql = window.matchMedia(mq);
const listener = (e: any) => setMatch(e.matches);
mql.addEventListener('change', listener);
return () => mql.removeEventListener('change', listener);
}
}, [mq]);
return matches;
}