Skip to content

Commit

Permalink
Merge pull request #112 from PrefectHQ/unmount-watchers
Browse files Browse the repository at this point in the history
BugFix: stop watchers during the `beforeRouteLeave` lifecycle
pleek91 authored Oct 17, 2022

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
2 parents 56ee8ef + 2df6bc5 commit 7b8ee5a
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/useRouteQueryParam/useRouteQueryParam.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable no-redeclare */
import { Ref, ref, watch } from 'vue'
import { RouteLocationNormalized, useRoute, useRouter } from 'vue-router'
import { onBeforeRouteLeave, RouteLocationNormalized, useRoute, useRouter } from 'vue-router'

export function useRouteQueryParam(param: string): Ref<string | string[]>
export function useRouteQueryParam(param: string, defaultValue: string): Ref<string>
@@ -11,15 +11,15 @@ export function useRouteQueryParam(param: string, defaultValue: string | string[
const initialValue = matchValueType(defaultValue, getRouteQueryParam(route, param) ?? defaultValue)
const valueRef = ref<string | string[]>(initialValue)

watch(valueRef, (newValue, oldValue) => {
const unwatchValue = watch(valueRef, (newValue, oldValue) => {
if (isSame(newValue, oldValue)) {
return
}

router.push({ query: { ...route.query, [param]: valueRef.value } })
})

watch(route, (newRoute, oldRoute) => {
const unwatchRoute = watch(route, (newRoute, oldRoute) => {
const newValue = getRouteQueryParam(newRoute, param) ?? defaultValue
const oldValue = getRouteQueryParam(oldRoute, param) ?? defaultValue
const matched = matchValueType(oldValue, newValue)
@@ -29,6 +29,11 @@ export function useRouteQueryParam(param: string, defaultValue: string | string[
}
}, { deep: true })

onBeforeRouteLeave(() => {
unwatchValue()
unwatchRoute()
})

return valueRef
}

0 comments on commit 7b8ee5a

Please sign in to comment.