# Vue

> @trpc12/tanstack-vue-query: a Vue plugin or provideTrpc() for the client, useTrpc() in setup, and useSubscription with refs.

`@trpc12/tanstack-vue-query` re-exports [`@trpc12/tanstack-query`](https://v12.trpc.io/docs/integrations/tanstack-query.md) and adds an app plugin (or `provideTrpc()`) that provides a client and its helpers, and a `useSubscription` that returns refs.

```package-install
@trpc12/trpc @trpc12/tanstack-vue-query @tanstack/vue-query
```

## Provide the client

`createTrpcContext` takes the type of the function that makes the client (or of the client, or the router), so the helpers get what its links declare. Install its plugin next to `VueQueryPlugin`:

```ts
// trpc.ts
const makeClient = () =>
  createTrpcClient({
    router: routerType<AppRouter>(),
    links: [httpLink({ url: '/trpc' })],
  });
export const { TrpcPlugin, useTrpc, useTrpcClient } =
  createTrpcContext<typeof makeClient>();

// main.ts
createApp(App)
  .use(VueQueryPlugin)
  .use(TrpcPlugin, { client: makeClient() })
  .mount('#app');
```

`provideTrpc(client)` provides it to one component's descendants instead, for a client per subtree or per test. `useTrpcClient()` returns the client itself, for calls outside TanStack Query.

## Queries and mutations

Pass a getter to `useQuery`, so the options follow reactive input; a new input is a new key:

```ts
// in <script setup>
const trpc = useTrpc();
const queryClient = useQueryClient();
const id = ref('1');

const post = useQuery(() =>
  trpc.post.byId.queryOptions({ input: { id: id.value } }),
);
post.data.value?.title;
// (property) title: string | undefined
const create = useMutation(
  trpc.post.create.mutationOptions({
    onSuccess: () => queryClient.invalidateQueries(trpc.post.pathFilter()),
  }),
);
```

## Subscriptions

`useSubscription` subscribes while the component is mounted (or the effect scope is active) and returns refs: `status`, `data` (the latest event) and `error`, with `reset()`. Pass a getter or a ref, and a new input restarts it:

```ts
const channel = ref('general');
const added = useSubscription(() =>
  trpc.post.onAdd.subscriptionOptions({ input: { channel: channel.value } }),
);
const latest = computed(() =>
  added.status.value === 'connecting'
    ? 'Connecting…'
    : added.data.value?.data.title,
);
```

What subscriptions share, and the query-cache forms (`liveOptions()`, `streamedOptions()`), are in [Subscriptions](https://v12.trpc.io/docs/integrations/tanstack-query/subscriptions.md).
