Skip to content

[@mantine/hooks] use-media-query: Catch matchMedia errors when reading the initial value synchronously#9020

Open
mahirhir wants to merge 1 commit into
mantinedev:masterfrom
mahirhir:use-media-query-guard-initial-matchmedia
Open

[@mantine/hooks] use-media-query: Catch matchMedia errors when reading the initial value synchronously#9020
mahirhir wants to merge 1 commit into
mantinedev:masterfrom
mahirhir:use-media-query-guard-initial-matchmedia

Conversation

@mahirhir

Copy link
Copy Markdown

#8189 fixed a Safari crash where window.matchMedia exists but throws when called inside a cross-origin iframe. That PR wrapped the call inside the effect in a try/catch, but the same call in getInitialValue was left unguarded:

if (typeof window !== 'undefined' && 'matchMedia' in window) {
  return window.matchMedia(query).matches;
}

getInitialValue runs during render when a consumer passes { getInitialValueInEffect: false } (used to read the value synchronously and avoid a flash on first paint). The 'matchMedia' in window check only confirms the method exists, which is exactly the case in the Safari iframe scenario, so the call still throws and crashes the render. The effect path no longer crashes after #8189, but this synchronous path does.

The fix mirrors #8189: wrap the call in try/catch and fall back to false.

Added a test that makes matchMedia throw and renders with getInitialValueInEffect: false. Without the change the render throws; with it the hook returns false.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant