Skip to content

Commit

Permalink
fix: make useMedia work on server
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich authored Jul 27, 2019
2 parents eee705b + 7d9f821 commit 2349f0c
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ type MediaQueryObject = { [key: string]: string | number | boolean };
const camelToHyphen = (str: string) =>
str.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`).toLowerCase();

const noWindowMatches: MediaQueryList = {
media: '',
addListener: noop,
removeListener: noop,
matches: false,
onchange: noop,
addEventListener: noop,
removeEventListener: noop,
dispatchEvent: (_: Event) => true
};

const objectToString = (query: string | MediaQueryObject) => {
if (typeof query === 'string') return query;
return Object.entries(query)
Expand All @@ -33,7 +44,10 @@ const createUseMedia = (effect: Effect) => (
const query = objectToString(rawQuery);
effect(() => {
let mounted = true;
const mql = window.matchMedia(query);
const mql =
typeof window === 'undefined'
? noWindowMatches
: window.matchMedia(query);
const onChange = () => {
if (!mounted) return;
setState(!!mql.matches);
Expand All @@ -51,6 +65,7 @@ const createUseMedia = (effect: Effect) => (
return state;
};

function noop() {}

export const useMedia = createUseMedia(useEffect);
export const useMediaLayout = createUseMedia(useLayoutEffect);
Expand Down

0 comments on commit 2349f0c

Please sign in to comment.