Skip to content

Commit

Permalink
fix(useMediaQuery): only add/remove event listeners on query change
Browse files Browse the repository at this point in the history
  • Loading branch information
Ingramz committed Jul 16, 2023
1 parent 658444b commit 4cf721b
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 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,25 +21,28 @@ export function useMediaQuery(query: MaybeRefOrGetter<string>, options: Configur
let mediaQuery: MediaQueryList | undefined
const matches = ref(false)

const update = (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)
else
// @ts-expect-error deprecated API
// eslint-disable-next-line @typescript-eslint/no-use-before-define
mediaQuery.removeListener(update)
mediaQuery = undefined
}

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

cleanup()

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

if (!mediaQuery)
Expand All @@ -50,10 +53,11 @@ export function useMediaQuery(query: MaybeRefOrGetter<string>, options: Configur
else
// @ts-expect-error deprecated API
mediaQuery.addListener(update)
}
watchEffect(update)

tryOnScopeDispose(() => cleanup())
return cleanup
})

tryOnScopeDispose(stopWatch)

return matches
}

0 comments on commit 4cf721b

Please sign in to comment.