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/useCache.md
View on GitHub<!-- Generated by `yarn build:skills` from docs/core/api/useCache.md (vue). Edit the source doc, not this file. -->
# useCache()
Data rendering without the fetch.
Access any [Endpoint](https://dataclient.io/rest/api/Endpoint)'s response. Returns `undefined` until it is fetched, set, or
inferable from entities already in the store, and again after invalidation (see [Behavior](#behavior)).
That means "not loaded", not "doesn't exist on the server", so use it for data other code loads, like
the current user a login flow fetches.
`useCache()` is reactive to data [mutations](./mutations.md); rerendering only when necessary.
## Usage
```ts title="UserResource"
import { Entity, resource } from '@data-client/rest';
export class User extends Entity {
id = '';
name = '';
isAdmin = false;
static key = 'User';
}
export const UserResource = resource({
path: '/users/:id',
schema: User,
}).extend('current', {
path: '/user',
schema: User,
});
```
```html title="Unauthed.vue"
<script setup lang="ts">
import { useController, useLoading } from '@data-client/vue';
import { UserResource } from './UserResource';
const ctrl = useController();
const [handleLogin, loading] = useLoading(() =>
ctrl.fetch(UserResource.current),
);
</script>
<template>
<div>
<p>Not authorized</p>
<template v-if="loading">logging in...</template>
<button v-else @click="handleLogin">Login</button>
</div>
</template>
```
```html title="Authorized.vue"
<script setup lang="ts">
import { useController } from '@data-client/vue';
import { UserResource, type User } from './UserResource';
defineProps<{ user: User }>();
const ctrl = useController();
const handleLogout = () => ctrl.invalidate(UserResource.current);
</script>
<template>
<div>
<p>Welcome, {{ user.name }}!</p>
<button @click="handleLogout">Logout</button>
</div>
</template>
```
```html title="AuthorizedPage.vue" {8}
<script setup lang="ts">
import { useCache } from '@data-client/vue';
import { UserResource } from './UserResource';
import Unauthed from './Unauthed.vue';
import Authorized from './Authorized.vue';
// currentUser as ComputedRef<User | undefined>
const currentUser = useCache(UserResource.current);
</script>
<template>
<!-- currentUser is unwrapped in the template -->
<Authorized v-if="currentUser" :user="currentUser" />
<!-- user is not logged in -->
<Unauthed v-else />
</template>
```
See [truthiness narrowing](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#truthiness-narrowing) for
more information about type handling
## Behavior
`useCache()` returns a [ComputedRef](https://vuejs.org/api/reactivity-core.html#computed). The table
below describes its `.value`.
| Expiry Status | Returns | Conditions |
| ------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Invalid | `undefined` | not in store, [deletion](https://dataclient.io/rest/api/resource#delete), [invalidation](./Controller.md#invalidate), [invalidIfStale](https://dataclient.io/vue/concepts/expiry-policy#endpointinvalidifstale) |
| Stale | denormalized | (first-render, arg change) & [expiry < now](https://dataclient.io/vue/concepts/expiry-policy) |
| Valid | denormalized | fetch completion |
| | `undefined` | `null` used as second argument |
> **Tip: Conditional Dependencies**
>
> Use `null` as the second argument to any Data Client hook means "do nothing."
> A [RestEndpoint](https://dataclient.io/rest/api/RestEndpoint) without path or search params takes `{}` in its place, like `enabled ? {} : null`.
>
> ```typescript
> // todo could be undefined if id is undefined
> const todo = useCache(
> TodoResource.get,
> computed(() => (id.value ? { id: id.value } : null)),
> );
> ```
## Types
```typescript
function useCache(
endpoint: ReadEndpoint,
...args: MaybeRefsOrGetters<Parameters<typeof endpoint.key>> | [null]
): ComputedRef<DenormalizeNullable<typeof endpoint.schema>>;
```
Arguments can be plain values, [refs](https://vuejs.org/api/reactivity-core.html#ref) (including [computed](https://vuejs.org/api/reactivity-core.html#computed)), or getter
functions like `() => ({ id: props.id })`. A plain object like `{ id: props.id }` is read once and won't
follow prop or route changes, so use a getter or `computed` when an argument can change.
The result updates when the arguments change.
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 |