Skip to content

Commit

Permalink
fix(nuxt3): enable useAsyncData and useFetch usage within plugins (
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored Nov 15, 2021
1 parent fb2e8cc commit 4a3ba73
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
4 changes: 2 additions & 2 deletions docs/content/3.docs/1.usage/1.data-fetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand Down
8 changes: 4 additions & 4 deletions packages/nuxt3/src/app/composables/asyncData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(() => {
Expand Down Expand Up @@ -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()
}
}
Expand Down

0 comments on commit 4a3ba73

Please sign in to comment.