Skip to content

Commit

Permalink
perf(nuxt): unsubscribe from watch when scope is disposed (#26554)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe committed Apr 3, 2024
1 parent 2f89151 commit cbb4a1c
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions packages/nuxt/src/app/composables/asyncData.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computed, getCurrentInstance, onBeforeMount, onServerPrefetch, onUnmounted, ref, shallowRef, toRef, unref, watch } from 'vue'
import { computed, getCurrentInstance, getCurrentScope, onBeforeMount, onScopeDispose, onServerPrefetch, onUnmounted, ref, shallowRef, toRef, unref, watch } from 'vue'
import type { Ref, WatchSource } from 'vue'
import type { NuxtApp } from '../nuxt'
import { useNuxtApp } from '../nuxt'
Expand Down Expand Up @@ -223,8 +223,8 @@ export function useAsyncData<

const promise = nuxtApp.runWithContext(_handler)

nuxtApp.ssrContext!._sharedPrerenderCache!.set(key, promise)
return promise
nuxtApp.ssrContext!._sharedPrerenderCache!.set(key, promise)
return promise
}

// Used to get default values
Expand Down Expand Up @@ -370,16 +370,20 @@ export function useAsyncData<
// 4. Navigation (lazy: false) - or plugin usage: await fetch
initialFetch()
}
const hasScope = getCurrentScope()
if (options.watch) {
watch(options.watch, () => asyncData.refresh())
const unsub = watch(options.watch, () => asyncData.refresh())
if (hasScope) {
onScopeDispose(unsub)
}
}
const off = nuxtApp.hook('app:data:refresh', async (keys) => {
if (!keys || keys.includes(key)) {
await asyncData.refresh()
}
})
if (instance) {
onUnmounted(off)
if (hasScope) {
onScopeDispose(off)
}
}

Expand Down

0 comments on commit cbb4a1c

Please sign in to comment.