PRINCESSELSA
PRINCESSELSA4w ago

How to wrap response type with useAsyncData from Nuxt?

I'm using the vanilla client with Nuxt currently but it's a little tedious calling useAsyncData(() => client.someProcedure.query()) on every call so that I don't double fetch during SSR. Is there a way to make a wrapper client that will wrap query and mutation responses with the useAsyncData() call? I would love if the client was typed and I could call it the same way I can call the vanilla client.
1 Reply
PRINCESSELSA
PRINCESSELSAOP4w ago
I currently have this working but I'm not sure how to fix the typings so that the return type is inferred correctly as AsyncData<ReturnType> Proxy code:
function createNuxtTRPCClient(client: CreateTRPCClient<AppRouter>) {
return new Proxy(client, {
get(obj, target) {
return createNuxtTRPCClient(obj[target])
},
async apply(target, thisArg, args) {
return useAsyncData(() => target.apply(thisArg, args))
}
})
}
function createNuxtTRPCClient(client: CreateTRPCClient<AppRouter>) {
return new Proxy(client, {
get(obj, target) {
return createNuxtTRPCClient(obj[target])
},
async apply(target, thisArg, args) {
return useAsyncData(() => target.apply(thisArg, args))
}
})
}

Did you find this page helpful?