mirror of
https://codeberg.org/MarkusThielker/finances.git
synced 2025-04-18 16:41:18 +00:00
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) {
|
export function useMediaQuery(mq: string) {
|
||||||
|
|
||||||
const mql = useMemo(() => matchMedia(mq), [mq]);
|
const [matches, setMatch] = useState(
|
||||||
const [matches, setMatch] = useState(mql.matches);
|
() => typeof window !== 'undefined' ? window.matchMedia(mq).matches : false,
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const listener = (e: any) => setMatch(e.matches);
|
if (typeof window !== 'undefined') {
|
||||||
mql.addEventListener('change', listener);
|
const mql = window.matchMedia(mq);
|
||||||
|
const listener = (e: any) => setMatch(e.matches);
|
||||||
return () => mql.removeEventListener('change', listener);
|
mql.addEventListener('change', listener);
|
||||||
}, [mq, mql]);
|
return () => mql.removeEventListener('change', listener);
|
||||||
|
}
|
||||||
|
}, [mq]);
|
||||||
|
|
||||||
return matches;
|
return matches;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue