Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(useMediaQuery): only add/remove event listeners on query change #3236

Merged
merged 6 commits into from
Jul 30, 2023
35 changes: 19 additions & 16 deletions packages/core/useMediaQuery/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { ref, watchEffect } from 'vue-demi'
import type { MaybeRefOrGetter } from '@vueuse/shared'
import { toRef, tryOnScopeDispose } from '@vueuse/shared'
import { toValue, tryOnScopeDispose } from '@vueuse/shared'
import type { ConfigurableWindow } from '../_configurable'
import { defaultWindow } from '../_configurable'
import { useSupported } from '../useSupported'
Expand All @@ -21,39 +21,42 @@ export function useMediaQuery(query: MaybeRefOrGetter<string>, options: Configur
let mediaQuery: MediaQueryList | undefined
const matches = ref(false)

const handler = (event: MediaQueryListEvent) => {
matches.value = event.matches
}

const cleanup = () => {
if (!mediaQuery)
return
if ('removeEventListener' in mediaQuery)
// eslint-disable-next-line @typescript-eslint/no-use-before-define
mediaQuery.removeEventListener('change', update)
mediaQuery.removeEventListener('change', handler)
else
// @ts-expect-error deprecated API
// eslint-disable-next-line @typescript-eslint/no-use-before-define
mediaQuery.removeListener(update)
mediaQuery.removeListener(handler)
}

const update = () => {
const stopWatch = watchEffect(() => {
if (!isSupported.value)
return

cleanup()

mediaQuery = window!.matchMedia(toRef(query).value)
matches.value = !!mediaQuery?.matches

if (!mediaQuery)
return
mediaQuery = window!.matchMedia(toValue(query))

if ('addEventListener' in mediaQuery)
mediaQuery.addEventListener('change', update)
mediaQuery.addEventListener('change', handler)
else
// @ts-expect-error deprecated API
mediaQuery.addListener(update)
}
watchEffect(update)
mediaQuery.addListener(handler)

tryOnScopeDispose(() => cleanup())
matches.value = mediaQuery.matches
})

tryOnScopeDispose(() => {
stopWatch()
cleanup()
mediaQuery = undefined
})

return matches
}