Created
June 2, 2022 17:51
-
-
Save wobsoriano/6ad4abd84c67de79d68837ad2fce26d1 to your computer and use it in GitHub Desktop.
Nuxt 3 useAsyncData with server errors on client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
} | |
} |
Author
wobsoriano
commented
Jun 2, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment