mirror of
https://github.com/ArthurDanjou/trpc-nuxt.git
synced 2026-01-25 09:20:33 +01:00
save trpc server error to client
This commit is contained in:
@@ -26,6 +26,8 @@ const addTodo = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { data: todos, pending, error, refresh } = await $client.todo.getTodos.query()
|
const { data: todos, pending, error, refresh } = await $client.todo.getTodos.query()
|
||||||
|
|
||||||
|
console.log(typeof $client.todo.getTodos.query)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
|
|||||||
@@ -38,18 +38,38 @@ export function createNuxtProxyDecoration<TRouter extends AnyRouter>(name: strin
|
|||||||
const queryKey = getQueryKey(path, input)
|
const queryKey = getQueryKey(path, input)
|
||||||
|
|
||||||
if (lastArg === 'mutate') {
|
if (lastArg === 'mutate') {
|
||||||
// @ts-ignore: nuxt internal
|
return useAsyncDataWithError(queryKey, () => (client as any)[path][lastArg](input), {
|
||||||
return useAsyncData(() => (client as any)[path][lastArg](input), {
|
|
||||||
...asyncDataOptions as Record<string, any>,
|
...asyncDataOptions as Record<string, any>,
|
||||||
immediate: false,
|
immediate: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// @ts-ignore: nuxt internal
|
return useAsyncDataWithError(queryKey, () => (client as any)[path][lastArg](input), asyncDataOptions as Record<string, any>)
|
||||||
return useAsyncData(queryKey, () => (client as any)[path][lastArg](input), asyncDataOptions as Record<string, any>)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Custom useAsyncData to add server error to client
|
||||||
|
*/
|
||||||
|
async function useAsyncDataWithError(queryKey: string, cb: any, asyncDataOptions: any) {
|
||||||
|
// @ts-ignore: nuxt internal
|
||||||
|
const serverError = useState(`error-${queryKey}`, () => null)
|
||||||
|
// @ts-ignore: nuxt internal
|
||||||
|
const { error, data, ...rest } = await useAsyncData(queryKey, cb, asyncDataOptions)
|
||||||
|
|
||||||
|
if (error.value && !serverError.value)
|
||||||
|
serverError.value = error.value as any
|
||||||
|
|
||||||
|
if (data.value)
|
||||||
|
serverError.value = null
|
||||||
|
|
||||||
|
return {
|
||||||
|
...rest,
|
||||||
|
data,
|
||||||
|
error: serverError,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function createTRPCNuxtProxyClient<TRouter extends AnyRouter>(opts: CreateTRPCClientOptions<TRouter>) {
|
export function createTRPCNuxtProxyClient<TRouter extends AnyRouter>(opts: CreateTRPCClientOptions<TRouter>) {
|
||||||
const client = createTRPCProxyClient(opts)
|
const client = createTRPCProxyClient(opts)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user