reactive/data-client / .agents/skills/data-client-vue
data-client-vue
UnverifiedRead, change and render async and shared state in Vue with @data-client/vue: any data from an API or other async source, and global state shared across components (it has to persist somewhere, which makes it async). Use it for loading and error states, mutations and forms, filtered or derived views, and debugging data that looks wrong or stale on screen. Use it in place of fetch in onMounted or watch, or app-wide refs and provide/inject; its main composables are useSuspense, useQuery and useController.
references/useController.md
View on GitHub<!-- Generated by `yarn build:skills` from docs/core/api/useController.md (vue). Edit the source doc, not this file. -->
# useController()
[Controller](./Controller.md) provides type-safe methods to access and dispatch actions to the store.
For instance [fetch](./Controller.md#fetch), [invalidate](./Controller.md#invalidate),
and [setResponse](./Controller.md#setResponse)
```html {6}
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { MyResource } from './resources';
const props = defineProps<{ id: string }>();
const ctrl = useController();
const handleRefresh = async () => {
await ctrl.fetch(MyResource.get, { id: props.id });
};
const handleSuspend = async () => {
await ctrl.invalidate(MyResource.get, { id: props.id });
};
const handleLogout = () => {
ctrl.resetEntireStore();
};
</script>
```
`useController()` must be called inside `<script setup>` (or `setup()`), and requires the
[DataClientPlugin](./DataClientPlugin.md) to be installed.
The same [Controller](./Controller.md) is also available in templates and the Options API as [`$dataClient`](./DataClientPlugin.md#dataclient).
## Examples
### Form submission
[fetch](./Controller.md#fetch) returns the denormalized response, matching [useSuspense()](./useSuspense.md)'s return type. This allows using Entity methods like `pk()`.
```html title="CreatePost.vue"
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { useRouter } from 'vue-router';
import { PostResource } from './PostResource';
const ctrl = useController();
const router = useRouter();
const handleSubmit = async (e: Event) => {
e.preventDefault();
const post = await ctrl.fetch(
PostResource.getList.push,
new FormData(e.target as HTMLFormElement),
);
post.title;
post.computedField;
router.push(`/post/${post.pk()}`);
};
</script>
<template>
<form @submit="handleSubmit"><!-- fields --></form>
</template>
```
### Direct entity update
Use [set](./Controller.md#set) for immediate updates without network requests. Supports functional updates to avoid race conditions.
```html title="VoteButton.vue"
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { Article } from './Article';
const props = defineProps<{ articleId: string }>();
const ctrl = useController();
const vote = () =>
ctrl.set(Article, { id: props.articleId }, article => ({
...article,
votes: article.votes + 1,
}));
</script>
<template>
<button @click="vote">Vote</button>
</template>
```
### Invalidate after mutation
Force refetch of related data using [invalidate](./Controller.md#invalidate) or [expireAll](./Controller.md#expireAll).
```html title="ClearUserCache.vue"
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { UserResource } from './UserResource';
const ctrl = useController();
const handleClear = async () => {
// invalidate() causes suspense; expireAll() refetches silently
ctrl.expireAll(UserResource.get);
ctrl.expireAll(UserResource.getList);
};
</script>
<template>
<button @click="handleClear">Refresh user data</button>
</template>
```
> **Tip**
>
> For better performance and consistency, prefer [including side effect updates in mutation responses](https://dataclient.io/rest/guides/side-effects).
### Prefetching
Use [fetchIfStale](./Controller.md#fetchIfStale) to prefetch without overfetching fresh data.
```html title="ArticleLink.vue"
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { ArticleResource } from './ArticleResource';
const props = defineProps<{ id: string }>();
const ctrl = useController();
const prefetch = () =>
ctrl.fetchIfStale(ArticleResource.get, { id: props.id });
</script>
<template>
<RouterLink :to="`/article/${id}`" @mouseenter="prefetch">
Read more
</RouterLink>
</template>
```
### Websocket updates
Populate cache with external data via [set](./Controller.md#set).
```ts title="useWebsocket.ts"
import { onMounted, onUnmounted } from 'vue';
import { useController } from '@data-client/vue';
import { EntityMap } from './resources';
export function useWebsocket(url: string) {
const ctrl = useController();
let ws: WebSocket;
onMounted(() => {
ws = new WebSocket(url);
ws.onmessage = event => {
const { entity, args, data } = JSON.parse(event.data);
ctrl.set(EntityMap[entity], args, data);
};
});
onUnmounted(() => ws?.close());
}
```
> **Warning**
>
> For production use, implement a [Manager for data streams](https://dataclient.io/vue/concepts/managers#data-stream) rather than component-level lifecycle hooks. Managers handle connection lifecycle globally and work with SSR.
### Todo App
Example app: [vue-todo-app](https://github.com/reactive/data-client/tree/master/examples/vue-todo-app) ([`src/resources/TodoResource.ts`](https://github.com/reactive/data-client/blob/master/examples/vue-todo-app/src/resources/TodoResource.ts), [`src/components/TodoItem.vue`](https://github.com/reactive/data-client/blob/master/examples/vue-todo-app/src/components/TodoItem.vue))
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 319k | Updated | Claude CodeCodex | Verified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |