From c20a092a313e2342eea97b99583d39e2204e7b2f Mon Sep 17 00:00:00 2001 From: wobsoriano Date: Sun, 13 Nov 2022 10:37:24 -0800 Subject: [PATCH] docs: add tips section --- .../1.get-started/3.tips/1.composables.md | 40 +++++++++++++++++++ docs/content/1.get-started/index.md | 4 ++ 2 files changed, 44 insertions(+) create mode 100644 docs/content/1.get-started/3.tips/1.composables.md create mode 100644 docs/content/1.get-started/index.md diff --git a/docs/content/1.get-started/3.tips/1.composables.md b/docs/content/1.get-started/3.tips/1.composables.md new file mode 100644 index 0000000..d49af24 --- /dev/null +++ b/docs/content/1.get-started/3.tips/1.composables.md @@ -0,0 +1,40 @@ +--- +title: Composables +--- + +# Composables + +It is often useful to wrap functionality of your `@trpc/client` api within other functions. For this purpose, it's necessary to be able to infer input types and output types generated by your `@trpc/server` router. + +## Inference Helpers + +`@trpc/server` exports the following helper types to assist with inferring these types from the `AppRouter` exported by your `@trpc/server` router: + +- `inferRouterInputs` +- `inferRouterOutputs` + +Let's assume we have this example composable using Nuxt's [useAsyncData](https://v3.nuxtjs.org/api/composables/use-async-data/): + +```ts +const { data, error } = await useAsyncData(() => $client.todo.getTodos.query()) +``` + +We can wrap this in a composable and also set the client error types: + +```ts [composables/useGetTodos.ts] +import { TRPCClientError } from '@trpc/client' +import type { inferRouterOutputs } from '@trpc/server' +import type { AppRouter } from '@/server/trpc/routers' + +type RouterOutput = inferRouterOutputs +type GetTodosOutput = RouterOutput['todo']['getTodos'] + +type ErrorOutput = TRPCClientError + +export default function useGetTodos() { + const { $client } = useNuxtApp() + return useAsyncData(() => $client.todo.getTodos.query()) +} +``` + +Now, we have a fully-typed composable. diff --git a/docs/content/1.get-started/index.md b/docs/content/1.get-started/index.md new file mode 100644 index 0000000..b3af995 --- /dev/null +++ b/docs/content/1.get-started/index.md @@ -0,0 +1,4 @@ +--- +navigation: false +redirect: /get-started/installation +---