fix(nuxt3): enable useAsyncData and useFetch usage within plugins (#1933)

This commit is contained in:
Daniel Roe 2021-11-15 16:34:39 +00:00 committed by GitHub
parent fb2e8ccba5
commit 4a3ba73f22
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 6 deletions

View File

@ -8,7 +8,7 @@ Nuxt provides `useFetch`, `useLazyFetch`, `useAsyncData` and `useLazyAsyncData`
## `useAsyncData`
Within your pages and components you can use `useAsyncData` to get access to data that resolves asynchronously.
Within your pages, components and plugins you can use `useAsyncData` to get access to data that resolves asynchronously.
### Usage
@ -57,7 +57,7 @@ This composable behaves identically to `useAsyncData` with the `lazy: true` opti
## `useFetch`
Within your pages and components you can use `useFetch` to get universally fetch from any URL.
Within your pages, components and plugins you can use `useFetch` to universally fetch from any URL.
This composable provides a convenient wrapper around `useAsyncData` and `$fetch` and automatically generates a key based on url and fetch options and infers API response type.

View File

@ -61,7 +61,7 @@ export function useAsyncData<
// Setup hook callbacks once per instance
const instance = getCurrentInstance()
if (!instance._nuxtOnBeforeMountCbs) {
if (instance && !instance._nuxtOnBeforeMountCbs) {
const cbs = instance._nuxtOnBeforeMountCbs = []
if (instance && process.client) {
onBeforeMount(() => {
@ -125,15 +125,15 @@ export function useAsyncData<
asyncData.pending.value = false
}
// 2. Initial load (server: false): fetch on mounted
if (nuxt.isHydrating && clientOnly) {
if (instance && nuxt.isHydrating && clientOnly) {
// Fetch on mounted (initial load or lazy fetch)
instance._nuxtOnBeforeMountCbs.push(asyncData.refresh)
} else if (!nuxt.isHydrating) { // Navigation
if (options.lazy) {
if (instance && options.lazy) {
// 3. Navigation (lazy: true): fetch on mounted
instance._nuxtOnBeforeMountCbs.push(asyncData.refresh)
} else {
// 4. Navigation (lazy: false): await fetch
// 4. Navigation (lazy: false) - or plugin usage: await fetch
asyncData.refresh()
}
}