mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-11 00:23:53 +00:00
fix(nuxt)!: improve default asyncData
value behaviour (#27718)
This commit is contained in:
parent
bbad9bf534
commit
57e84086cc
@ -209,6 +209,7 @@ Previously `data` was initialized to `null` but reset in `clearNuxtData` to `und
|
||||
If you encounter any issues you can revert back to the previous behavior with:
|
||||
|
||||
```ts twoslash [nuxt.config.ts]
|
||||
// @errors: 2353
|
||||
export default defineNuxtConfig({
|
||||
experimental: {
|
||||
defaults: {
|
||||
@ -232,10 +233,10 @@ Please report an issue if you are doing this, as we do not plan to keep this as
|
||||
Previously it was possible to pass `dedupe: boolean` to `refresh`. These were aliases of `cancel` (`true`) and `defer` (`false`).
|
||||
|
||||
```ts twoslash [app.vue]
|
||||
// @errors: 2322
|
||||
const { refresh } = await useAsyncData(async () => ({ message: 'Hello, Nuxt 3!' }))
|
||||
|
||||
async function refreshData () {
|
||||
// @ts-expect-error this is no longer valid syntax
|
||||
await refresh({ dedupe: true })
|
||||
}
|
||||
```
|
||||
@ -281,6 +282,7 @@ Often users set an appropriately empty value, such as an empty array, to avoid t
|
||||
If you encounter any issues you can revert back to the previous behavior, for now, with:
|
||||
|
||||
```ts twoslash [nuxt.config.ts]
|
||||
// @errors: 2353
|
||||
export default defineNuxtConfig({
|
||||
experimental: {
|
||||
resetAsyncDataToUndefined: true,
|
||||
|
@ -8,10 +8,7 @@ import { createError } from './error'
|
||||
import { onNuxtReady } from './ready'
|
||||
|
||||
// @ts-expect-error virtual file
|
||||
import { asyncDataDefaults, resetAsyncDataToUndefined } from '#build/nuxt.config.mjs'
|
||||
|
||||
// TODO: temporary module for backwards compatibility
|
||||
import type { DedupeOption, DefaultAsyncDataErrorValue, DefaultAsyncDataValue } from '#app/defaults'
|
||||
import { asyncDataDefaults } from '#build/nuxt.config.mjs'
|
||||
|
||||
export type AsyncDataRequestStatus = 'idle' | 'pending' | 'success' | 'error'
|
||||
|
||||
@ -45,7 +42,7 @@ export interface AsyncDataOptions<
|
||||
ResT,
|
||||
DataT = ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> {
|
||||
/**
|
||||
* Whether to fetch on the server side.
|
||||
@ -107,7 +104,7 @@ export interface AsyncDataExecuteOptions {
|
||||
* Instead of using `boolean` values, use `cancel` for `true` and `defer` for `false`.
|
||||
* Boolean values will be removed in a future release.
|
||||
*/
|
||||
dedupe?: DedupeOption
|
||||
dedupe?: 'cancel' | 'defer'
|
||||
}
|
||||
|
||||
export interface _AsyncData<DataT, ErrorT> {
|
||||
@ -119,7 +116,7 @@ export interface _AsyncData<DataT, ErrorT> {
|
||||
refresh: (opts?: AsyncDataExecuteOptions) => Promise<void>
|
||||
execute: (opts?: AsyncDataExecuteOptions) => Promise<void>
|
||||
clear: () => void
|
||||
error: Ref<ErrorT | DefaultAsyncDataErrorValue>
|
||||
error: Ref<ErrorT | undefined>
|
||||
status: Ref<AsyncDataRequestStatus>
|
||||
}
|
||||
|
||||
@ -140,11 +137,11 @@ export function useAsyncData<
|
||||
NuxtErrorDataT = unknown,
|
||||
DataT = ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> (
|
||||
handler: (ctx?: NuxtApp) => Promise<ResT>,
|
||||
options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | DefaultAsyncDataErrorValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>
|
||||
/**
|
||||
* Provides access to data that resolves asynchronously in an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/api/composables/use-async-data}
|
||||
@ -160,7 +157,7 @@ export function useAsyncData<
|
||||
> (
|
||||
handler: (ctx?: NuxtApp) => Promise<ResT>,
|
||||
options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | DefaultAsyncDataErrorValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>
|
||||
/**
|
||||
* Provides access to data that resolves asynchronously in an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/api/composables/use-async-data}
|
||||
@ -173,12 +170,12 @@ export function useAsyncData<
|
||||
NuxtErrorDataT = unknown,
|
||||
DataT = ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> (
|
||||
key: string,
|
||||
handler: (ctx?: NuxtApp) => Promise<ResT>,
|
||||
options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | DefaultAsyncDataErrorValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>
|
||||
/**
|
||||
* Provides access to data that resolves asynchronously in an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/api/composables/use-async-data}
|
||||
@ -196,14 +193,14 @@ export function useAsyncData<
|
||||
key: string,
|
||||
handler: (ctx?: NuxtApp) => Promise<ResT>,
|
||||
options?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | DefaultAsyncDataErrorValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined>
|
||||
export function useAsyncData<
|
||||
ResT,
|
||||
NuxtErrorDataT = unknown,
|
||||
DataT = ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
> (...args: any[]): AsyncData<PickFrom<DataT, PickKeys>, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | DefaultAsyncDataErrorValue> {
|
||||
DefaultT = undefined,
|
||||
> (...args: any[]): AsyncData<PickFrom<DataT, PickKeys>, (NuxtErrorDataT extends Error | NuxtError ? NuxtErrorDataT : NuxtError<NuxtErrorDataT>) | undefined> {
|
||||
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
|
||||
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
|
||||
|
||||
@ -235,7 +232,7 @@ export function useAsyncData<
|
||||
}
|
||||
|
||||
// Used to get default values
|
||||
const getDefault = () => asyncDataDefaults.value
|
||||
const getDefault = () => undefined
|
||||
const getDefaultCachedData = () => nuxtApp.isHydrating ? nuxtApp.payload.data[key] : nuxtApp.static.data[key]
|
||||
|
||||
// Apply defaults
|
||||
@ -257,7 +254,7 @@ export function useAsyncData<
|
||||
|
||||
// Create or use a shared asyncData entity
|
||||
if (!nuxtApp._asyncData[key] || !options.immediate) {
|
||||
nuxtApp.payload._errors[key] ??= asyncDataDefaults.errorValue
|
||||
nuxtApp.payload._errors[key] ??= undefined
|
||||
|
||||
const _ref = options.deep ? ref : shallowRef
|
||||
|
||||
@ -319,7 +316,7 @@ export function useAsyncData<
|
||||
nuxtApp.payload.data[key] = result
|
||||
|
||||
asyncData.data.value = result
|
||||
asyncData.error.value = asyncDataDefaults.errorValue
|
||||
asyncData.error.value = undefined
|
||||
asyncData.status.value = 'success'
|
||||
})
|
||||
.catch((error: any) => {
|
||||
@ -416,11 +413,11 @@ export function useLazyAsyncData<
|
||||
DataE = Error,
|
||||
DataT = ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> (
|
||||
handler: (ctx?: NuxtApp) => Promise<ResT>,
|
||||
options?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | DefaultAsyncDataValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | undefined>
|
||||
export function useLazyAsyncData<
|
||||
ResT,
|
||||
DataE = Error,
|
||||
@ -430,18 +427,18 @@ export function useLazyAsyncData<
|
||||
> (
|
||||
handler: (ctx?: NuxtApp) => Promise<ResT>,
|
||||
options?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | DefaultAsyncDataValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | undefined>
|
||||
export function useLazyAsyncData<
|
||||
ResT,
|
||||
DataE = Error,
|
||||
DataT = ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> (
|
||||
key: string,
|
||||
handler: (ctx?: NuxtApp) => Promise<ResT>,
|
||||
options?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | DefaultAsyncDataValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | undefined>
|
||||
export function useLazyAsyncData<
|
||||
ResT,
|
||||
DataE = Error,
|
||||
@ -452,15 +449,15 @@ export function useLazyAsyncData<
|
||||
key: string,
|
||||
handler: (ctx?: NuxtApp) => Promise<ResT>,
|
||||
options?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | DefaultAsyncDataValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | undefined>
|
||||
|
||||
export function useLazyAsyncData<
|
||||
ResT,
|
||||
DataE = Error,
|
||||
DataT = ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
> (...args: any[]): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | DefaultAsyncDataValue> {
|
||||
DefaultT = undefined,
|
||||
> (...args: any[]): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE | undefined> {
|
||||
const autoKey = typeof args[args.length - 1] === 'string' ? args.pop() : undefined
|
||||
if (typeof args[0] !== 'string') { args.unshift(autoKey) }
|
||||
const [key, handler, options = {}] = args as [string, (ctx?: NuxtApp) => Promise<ResT>, AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>]
|
||||
@ -475,12 +472,12 @@ export function useLazyAsyncData<
|
||||
}
|
||||
|
||||
/** @since 3.1.0 */
|
||||
export function useNuxtData<DataT = any> (key: string): { data: Ref<DataT | DefaultAsyncDataValue> } {
|
||||
export function useNuxtData<DataT = any> (key: string): { data: Ref<DataT | undefined> } {
|
||||
const nuxtApp = useNuxtApp()
|
||||
|
||||
// Initialize value when key is not already set
|
||||
if (!(key in nuxtApp.payload.data)) {
|
||||
nuxtApp.payload.data[key] = asyncDataDefaults.value
|
||||
nuxtApp.payload.data[key] = undefined
|
||||
}
|
||||
|
||||
return {
|
||||
@ -532,12 +529,12 @@ function clearNuxtDataByKey (nuxtApp: NuxtApp, key: string): void {
|
||||
}
|
||||
|
||||
if (key in nuxtApp.payload._errors) {
|
||||
nuxtApp.payload._errors[key] = asyncDataDefaults.errorValue
|
||||
nuxtApp.payload._errors[key] = undefined
|
||||
}
|
||||
|
||||
if (nuxtApp._asyncData[key]) {
|
||||
nuxtApp._asyncData[key]!.data.value = resetAsyncDataToUndefined ? undefined : nuxtApp._asyncData[key]!._default()
|
||||
nuxtApp._asyncData[key]!.error.value = asyncDataDefaults.errorValue
|
||||
nuxtApp._asyncData[key]!.data.value = nuxtApp._asyncData[key]!._default()
|
||||
nuxtApp._asyncData[key]!.error.value = undefined
|
||||
nuxtApp._asyncData[key]!.pending.value = false
|
||||
nuxtApp._asyncData[key]!.status.value = 'idle'
|
||||
}
|
||||
|
@ -4,9 +4,6 @@ import { toRef } from 'vue'
|
||||
import { useNuxtApp } from '../nuxt'
|
||||
import { useRouter } from './router'
|
||||
|
||||
// @ts-expect-error virtual file
|
||||
import { nuxtDefaultErrorValue } from '#build/nuxt.config.mjs'
|
||||
|
||||
export const NUXT_ERROR_SIGNATURE = '__nuxt_error'
|
||||
|
||||
/** @since 3.0.0 */
|
||||
@ -50,7 +47,7 @@ export const clearError = async (options: { redirect?: string } = {}) => {
|
||||
await useRouter().replace(options.redirect)
|
||||
}
|
||||
|
||||
error.value = nuxtDefaultErrorValue
|
||||
error.value = undefined
|
||||
}
|
||||
|
||||
/** @since 3.0.0 */
|
||||
|
@ -8,9 +8,6 @@ import { useRequestFetch } from './ssr'
|
||||
import type { AsyncData, AsyncDataOptions, KeysOf, MultiWatchSources, PickFrom } from './asyncData'
|
||||
import { useAsyncData } from './asyncData'
|
||||
|
||||
// TODO: temporary module for backwards compatibility
|
||||
import type { DefaultAsyncDataErrorValue, DefaultAsyncDataValue } from '#app/defaults'
|
||||
|
||||
// @ts-expect-error virtual file
|
||||
import { fetchDefaults } from '#build/nuxt.config.mjs'
|
||||
|
||||
@ -33,7 +30,7 @@ export interface UseFetchOptions<
|
||||
ResT,
|
||||
DataT = ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
R extends NitroFetchRequest = string & {},
|
||||
M extends AvailableRouterMethod<R> = AvailableRouterMethod<R>,
|
||||
> extends Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'watch'>, ComputedFetchOptions<R, M> {
|
||||
@ -57,11 +54,11 @@ export function useFetch<
|
||||
_ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT,
|
||||
DataT = _ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> (
|
||||
request: Ref<ReqT> | ReqT | (() => ReqT),
|
||||
opts?: UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | DefaultAsyncDataErrorValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | undefined>
|
||||
/**
|
||||
* Fetch data from an API endpoint with an SSR-friendly composable.
|
||||
* See {@link https://nuxt.com/docs/api/composables/use-fetch}
|
||||
@ -80,7 +77,7 @@ export function useFetch<
|
||||
> (
|
||||
request: Ref<ReqT> | ReqT | (() => ReqT),
|
||||
opts?: UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | DefaultAsyncDataErrorValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | undefined>
|
||||
export function useFetch<
|
||||
ResT = void,
|
||||
ErrorT = FetchError,
|
||||
@ -89,7 +86,7 @@ export function useFetch<
|
||||
_ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT,
|
||||
DataT = _ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> (
|
||||
request: Ref<ReqT> | ReqT | (() => ReqT),
|
||||
arg1?: string | UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>,
|
||||
@ -195,11 +192,11 @@ export function useLazyFetch<
|
||||
_ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT,
|
||||
DataT = _ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> (
|
||||
request: Ref<ReqT> | ReqT | (() => ReqT),
|
||||
opts?: Omit<UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>, 'lazy'>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | DefaultAsyncDataErrorValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | undefined>
|
||||
export function useLazyFetch<
|
||||
ResT = void,
|
||||
ErrorT = FetchError,
|
||||
@ -212,7 +209,7 @@ export function useLazyFetch<
|
||||
> (
|
||||
request: Ref<ReqT> | ReqT | (() => ReqT),
|
||||
opts?: Omit<UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>, 'lazy'>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | DefaultAsyncDataErrorValue>
|
||||
): AsyncData<PickFrom<DataT, PickKeys> | DefaultT, ErrorT | undefined>
|
||||
export function useLazyFetch<
|
||||
ResT = void,
|
||||
ErrorT = FetchError,
|
||||
@ -221,7 +218,7 @@ export function useLazyFetch<
|
||||
_ResT = ResT extends void ? FetchResult<ReqT, Method> : ResT,
|
||||
DataT = _ResT,
|
||||
PickKeys extends KeysOf<DataT> = KeysOf<DataT>,
|
||||
DefaultT = DefaultAsyncDataValue,
|
||||
DefaultT = undefined,
|
||||
> (
|
||||
request: Ref<ReqT> | ReqT | (() => ReqT),
|
||||
arg1?: string | Omit<UseFetchOptions<_ResT, DataT, PickKeys, DefaultT, ReqT, Method>, 'lazy'>,
|
||||
|
@ -1,8 +0,0 @@
|
||||
// TODO: temporary module for backwards compatibility
|
||||
|
||||
export type DefaultAsyncDataErrorValue = null
|
||||
export type DefaultAsyncDataValue = null
|
||||
export type DefaultErrorValue = null
|
||||
export type DedupeOption = boolean | 'cancel' | 'defer'
|
||||
|
||||
export {}
|
@ -23,8 +23,6 @@ import type { ViewTransition } from './plugins/view-transitions.client'
|
||||
// @ts-expect-error virtual file
|
||||
import { appId } from '#build/nuxt.config.mjs'
|
||||
|
||||
// TODO: temporary module for backwards compatibility
|
||||
import type { DefaultAsyncDataErrorValue, DefaultErrorValue } from '#app/defaults'
|
||||
import type { NuxtAppLiterals } from '#app'
|
||||
|
||||
function getNuxtAppCtx (appName = appId || 'nuxt-app') {
|
||||
@ -94,8 +92,8 @@ export interface NuxtPayload {
|
||||
state: Record<string, any>
|
||||
once: Set<string>
|
||||
config?: Pick<RuntimeConfig, 'public' | 'app'>
|
||||
error?: NuxtError | DefaultErrorValue
|
||||
_errors: Record<string, NuxtError | DefaultAsyncDataErrorValue>
|
||||
error?: NuxtError | undefined
|
||||
_errors: Record<string, NuxtError | undefined>
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
@ -124,7 +122,7 @@ interface _NuxtApp {
|
||||
_asyncData: Record<string, {
|
||||
data: Ref<unknown>
|
||||
pending: Ref<boolean>
|
||||
error: Ref<Error | DefaultAsyncDataErrorValue>
|
||||
error: Ref<Error | undefined>
|
||||
status: Ref<AsyncDataRequestStatus>
|
||||
/** @internal */
|
||||
_default: () => unknown
|
||||
|
@ -127,7 +127,6 @@ async function initNuxt (nuxt: Nuxt) {
|
||||
// Add nuxt types
|
||||
nuxt.hook('prepare:types', (opts) => {
|
||||
opts.references.push({ types: 'nuxt' })
|
||||
opts.references.push({ path: resolve(nuxt.options.buildDir, 'types/app-defaults.d.ts') })
|
||||
opts.references.push({ path: resolve(nuxt.options.buildDir, 'types/plugins.d.ts') })
|
||||
// Add vue shim
|
||||
if (nuxt.options.typescript.shim) {
|
||||
|
@ -7,7 +7,7 @@ import escapeRE from 'escape-string-regexp'
|
||||
import { hash } from 'ohash'
|
||||
import { camelCase } from 'scule'
|
||||
import { filename } from 'pathe/utils'
|
||||
import type { NuxtTemplate, NuxtTypeTemplate } from 'nuxt/schema'
|
||||
import type { NuxtTemplate } from 'nuxt/schema'
|
||||
|
||||
import { annotatePlugins, checkForCircularDependencies } from './app'
|
||||
|
||||
@ -96,20 +96,6 @@ export const serverPluginTemplate: NuxtTemplate = {
|
||||
},
|
||||
}
|
||||
|
||||
export const appDefaults: NuxtTypeTemplate = {
|
||||
filename: 'types/app-defaults.d.ts',
|
||||
getContents: (ctx) => {
|
||||
const isV4 = ctx.nuxt.options.future.compatibilityVersion === 4
|
||||
return `
|
||||
declare module '#app/defaults' {
|
||||
type DefaultAsyncDataErrorValue = ${isV4 ? 'undefined' : 'null'}
|
||||
type DefaultAsyncDataValue = ${isV4 ? 'undefined' : 'null'}
|
||||
type DefaultErrorValue = ${isV4 ? 'undefined' : 'null'}
|
||||
type DedupeOption = ${isV4 ? '\'cancel\' | \'defer\'' : 'boolean | \'cancel\' | \'defer\''}
|
||||
}`
|
||||
},
|
||||
}
|
||||
|
||||
export const pluginsDeclaration: NuxtTemplate = {
|
||||
filename: 'types/plugins.d.ts',
|
||||
getContents: async (ctx) => {
|
||||
@ -418,13 +404,7 @@ export const nuxtConfigTemplate: NuxtTemplate = {
|
||||
`export const devRootDir = ${ctx.nuxt.options.dev ? JSON.stringify(ctx.nuxt.options.rootDir) : 'null'}`,
|
||||
`export const devLogs = ${JSON.stringify(ctx.nuxt.options.features.devLogs)}`,
|
||||
`export const nuxtLinkDefaults = ${JSON.stringify(ctx.nuxt.options.experimental.defaults.nuxtLink)}`,
|
||||
`export const asyncDataDefaults = ${JSON.stringify({
|
||||
...ctx.nuxt.options.experimental.defaults.useAsyncData,
|
||||
value: ctx.nuxt.options.experimental.defaults.useAsyncData.value === 'null' ? null : undefined,
|
||||
errorValue: ctx.nuxt.options.experimental.defaults.useAsyncData.errorValue === 'null' ? null : undefined,
|
||||
})}`,
|
||||
`export const resetAsyncDataToUndefined = ${ctx.nuxt.options.experimental.resetAsyncDataToUndefined}`,
|
||||
`export const nuxtDefaultErrorValue = ${ctx.nuxt.options.future.compatibilityVersion === 4 ? 'undefined' : 'null'}`,
|
||||
`export const asyncDataDefaults = ${JSON.stringify(ctx.nuxt.options.experimental.defaults.useAsyncData)}`,
|
||||
`export const fetchDefaults = ${JSON.stringify(fetchDefaults)}`,
|
||||
`export const vueAppRootContainer = ${ctx.nuxt.options.app.rootAttrs.id ? `'#${ctx.nuxt.options.app.rootAttrs.id}'` : `'body > ${ctx.nuxt.options.app.rootTag}'`}`,
|
||||
`export const viewTransition = ${ctx.nuxt.options.experimental.viewTransition}`,
|
||||
|
@ -397,23 +397,7 @@ export default defineUntypedSchema({
|
||||
* Options that apply to `useAsyncData` (and also therefore `useFetch`)
|
||||
*/
|
||||
useAsyncData: {
|
||||
/** @type {'undefined' | 'null'} */
|
||||
value: {
|
||||
async $resolve (val, get) {
|
||||
return val ?? ((await get('future') as Record<string, unknown>).compatibilityVersion === 4 ? 'undefined' : 'null')
|
||||
},
|
||||
},
|
||||
/** @type {'undefined' | 'null'} */
|
||||
errorValue: {
|
||||
async $resolve (val, get) {
|
||||
return val ?? ((await get('future') as Record<string, unknown>).compatibilityVersion === 4 ? 'undefined' : 'null')
|
||||
},
|
||||
},
|
||||
deep: {
|
||||
async $resolve (val, get) {
|
||||
return val ?? !((await get('future') as Record<string, unknown>).compatibilityVersion === 4)
|
||||
},
|
||||
},
|
||||
deep: false,
|
||||
},
|
||||
/** @type {Pick<typeof import('ofetch')['FetchOptions'], 'timeout' | 'retry' | 'retryDelay' | 'retryStatusCodes'>} */
|
||||
useFetch: {},
|
||||
@ -433,15 +417,5 @@ export default defineUntypedSchema({
|
||||
* @type {boolean}
|
||||
*/
|
||||
clientNodeCompat: false,
|
||||
|
||||
/**
|
||||
* Whether `clear` and `clearNuxtData` should reset async data to its _default_ value or update
|
||||
* it to `null`/`undefined`.
|
||||
*/
|
||||
resetAsyncDataToUndefined: {
|
||||
async $resolve (val, get) {
|
||||
return val ?? ((await get('future') as Record<string, unknown>).compatibilityVersion !== 4)
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
4
test/fixtures/basic-types/types.ts
vendored
4
test/fixtures/basic-types/types.ts
vendored
@ -12,8 +12,8 @@ import type { NavigateToOptions } from '#app/composables/router'
|
||||
import { NuxtLayout, NuxtLink, NuxtPage, ServerComponent, WithTypes } from '#components'
|
||||
import { useRouter } from '#imports'
|
||||
|
||||
// TODO: temporary module for backwards compatibility
|
||||
import type { DefaultAsyncDataErrorValue, DefaultAsyncDataValue } from '#app/defaults'
|
||||
type DefaultAsyncDataErrorValue = undefined
|
||||
type DefaultAsyncDataValue = undefined
|
||||
|
||||
interface TestResponse { message: string }
|
||||
|
||||
|
@ -20,11 +20,9 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { asyncDataDefaults } from '#build/nuxt.config.mjs'
|
||||
|
||||
const { data, execute } = await useAsyncData('immediateFalse', () => $fetch('/api/random'), { immediate: false })
|
||||
|
||||
if (data.value !== asyncDataDefaults.errorValue) {
|
||||
throw new Error(`Initial data should be ${asyncDataDefaults.errorValue}: ` + data.value)
|
||||
if (data.value !== undefined) {
|
||||
throw new Error(`Initial data should be undefined: ` + data.value)
|
||||
}
|
||||
</script>
|
||||
|
@ -20,8 +20,6 @@ import { callOnce } from '#app/composables/once'
|
||||
import { useLoadingIndicator } from '#app/composables/loading-indicator'
|
||||
import { useRouteAnnouncer } from '#app/composables/route-announcer'
|
||||
|
||||
import { asyncDataDefaults, nuxtDefaultErrorValue } from '#build/nuxt.config.mjs'
|
||||
|
||||
registerEndpoint('/api/test', defineEventHandler(event => ({
|
||||
method: event.method,
|
||||
headers: Object.fromEntries(event.headers.entries()),
|
||||
@ -128,7 +126,7 @@ describe('useAsyncData', () => {
|
||||
]
|
||||
`)
|
||||
expect(res instanceof Promise).toBeTruthy()
|
||||
expect(res.data.value).toBe(asyncDataDefaults.value)
|
||||
expect(res.data.value).toBe(undefined)
|
||||
await res
|
||||
expect(res.data.value).toBe('test')
|
||||
})
|
||||
@ -140,7 +138,7 @@ describe('useAsyncData', () => {
|
||||
expect(immediate.pending.value).toBe(false)
|
||||
|
||||
const nonimmediate = await useAsyncData(() => Promise.resolve('test'), { immediate: false })
|
||||
expect(nonimmediate.data.value).toBe(asyncDataDefaults.value)
|
||||
expect(nonimmediate.data.value).toBe(undefined)
|
||||
expect(nonimmediate.status.value).toBe('idle')
|
||||
expect(nonimmediate.pending.value).toBe(true)
|
||||
})
|
||||
@ -165,9 +163,9 @@ describe('useAsyncData', () => {
|
||||
// https://github.com/nuxt/nuxt/issues/23411
|
||||
it('should initialize with error set to null when immediate: false', async () => {
|
||||
const { error, execute } = useAsyncData(() => Promise.resolve({}), { immediate: false })
|
||||
expect(error.value).toBe(asyncDataDefaults.errorValue)
|
||||
expect(error.value).toBe(undefined)
|
||||
await execute()
|
||||
expect(error.value).toBe(asyncDataDefaults.errorValue)
|
||||
expect(error.value).toBe(undefined)
|
||||
})
|
||||
|
||||
it('should be accessible with useNuxtData', async () => {
|
||||
@ -208,9 +206,8 @@ describe('useAsyncData', () => {
|
||||
|
||||
clear()
|
||||
|
||||
// TODO: update to asyncDataDefaults.value in v4
|
||||
expect(data.value).toBeUndefined()
|
||||
expect(error.value).toBe(asyncDataDefaults.errorValue)
|
||||
expect(error.value).toBe(undefined)
|
||||
expect(pending.value).toBe(false)
|
||||
expect(status.value).toBe('idle')
|
||||
})
|
||||
@ -354,7 +351,7 @@ describe('errors', () => {
|
||||
showError('new error')
|
||||
expect(error.value).toMatchInlineSnapshot('[Error: new error]')
|
||||
clearError()
|
||||
expect(error.value).toBe(nuxtDefaultErrorValue)
|
||||
expect(error.value).toBe(undefined)
|
||||
})
|
||||
})
|
||||
|
||||
@ -620,7 +617,7 @@ describe('routing utilities: `abortNavigation`', () => {
|
||||
it('should throw an error if one is provided', () => {
|
||||
const error = useError()
|
||||
expect(() => abortNavigation({ message: 'Page not found' })).toThrowErrorMatchingInlineSnapshot('[Error: Page not found]')
|
||||
expect(error.value).toBe(nuxtDefaultErrorValue)
|
||||
expect(error.value).toBe(undefined)
|
||||
})
|
||||
it('should block navigation if no error is provided', () => {
|
||||
expect(abortNavigation()).toMatchInlineSnapshot('false')
|
||||
|
Loading…
Reference in New Issue
Block a user