Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Created June 2, 2022 17:51
Show Gist options
  • Save wobsoriano/6ad4abd84c67de79d68837ad2fce26d1 to your computer and use it in GitHub Desktop.
Save wobsoriano/6ad4abd84c67de79d68837ad2fce26d1 to your computer and use it in GitHub Desktop.
Nuxt 3 useAsyncData with server errors on client
import type {
AsyncData,
KeyOfRes,
PickFrom,
_Transform,
} from 'nuxt/dist/app/composables/asyncData'
import type { AsyncDataOptions, NuxtApp } from '#app'
export default async function useAsyncDataWithError<
DataT,
DataE = Error,
Transform extends _Transform<DataT> = _Transform<DataT, DataT>,
PickKeys extends KeyOfRes<Transform> = KeyOfRes<Transform>,
>(
key: string,
handler: (ctx?: NuxtApp) => Promise<DataT>,
options: AsyncDataOptions<DataT, Transform, PickKeys> = {},
): Promise<AsyncData<PickFrom<ReturnType<Transform>, PickKeys>, DataE | null | true>> {
const serverError = useState<DataE | true | null>(`error-${key}`, () => null)
const { error, data, ...rest } = await useAsyncData(key, handler, options)
// Only set the value on server and if serverError is empty
if (process.server && error.value && !serverError.value)
serverError.value = error.value as DataE | true | null
// Clear error if data is available
if (data.value)
serverError.value = null
return {
...rest,
data,
error: serverError,
}
}
@wobsoriano
Copy link
Author

const { error } = useAsyncDataWithError('key', () => $fetch('https://jsonplaceholder.typicode.com/404'))
// error value is same on both server and client

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment