N-FIN-33: fix hook accessing matchMedia while undefined
This commit is contained in:
parent
f0ee68beb2
commit
34a76cf93b
1 changed files with 13 additions and 8 deletions
|
@ -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;
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue