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/useSubscription.md
View on GitHub<!-- Generated by `yarn build:skills` from docs/core/api/useSubscription.md (vue). Edit the source doc, not this file. -->
# useSubscription()
Keeps data that changes often up to date.
The default [polling subscriptions](https://dataclient.io/vue/api/PollingSubscription) need
[pollFrequency](https://dataclient.io/rest/api/RestEndpoint#pollfrequency) set on the [Endpoint](https://dataclient.io/rest/api/Endpoint). Without it, subscribing
logs an error and does nothing.
> **Tip**
>
> [useLive()](./useLive.md) combines `useSubscription()` with [useSuspense()](./useSuspense.md) in one call.
## Usage
```typescript title="Ticker" {23}
import { Entity, RestEndpoint } from '@data-client/rest';
export class Ticker extends Entity {
product_id = '';
price = 0;
pk() {
return this.product_id;
}
static key = 'Ticker';
static schema = { price: Number };
}
export const getTicker = new RestEndpoint({
urlPrefix: 'https://api.exchange.coinbase.com',
path: '/products/:productId/ticker',
schema: Ticker,
process(value, { productId }) {
value.product_id = productId;
return value;
},
pollFrequency: 2000,
});
```
```html title="AssetPrice.vue" {10}
<script setup lang="ts">
import { useSuspense, useSubscription } from '@data-client/vue';
import NumberFlow from '@number-flow/vue';
import { getTicker } from './Ticker';
const props = defineProps<{ productId: string }>();
const ticker = await useSuspense(getTicker, () => ({
productId: props.productId,
}));
useSubscription(getTicker, () => ({ productId: props.productId }));
</script>
<template>
<dl class="stats">
<div>
<dt>{{ productId }}</dt>
<dd>
<NumberFlow
:value="ticker.price"
:format="{ style: 'currency', currency: 'USD' }"
/>
</dd>
</div>
</dl>
</template>
```
## Behavior
> **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 = useSubscription(
> TodoResource.get,
> computed(() => (id.value ? { id: id.value } : null)),
> );
> ```
The subscription is created when the component is set up and removed when it unmounts. When
an argument passed as a [ref](https://vuejs.org/api/reactivity-core.html#ref) changes, the previous
subscription is removed and a new one is created for the new arguments.
## Types
```typescript
function useSubscription(
endpoint: ReadEndpoint,
...args: MaybeRefsOrGetters<Parameters<typeof endpoint>> | [null]
): void;
```
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.
## Examples
### Only subscribe while element is visible
```typescript title="Ticker"
import { Entity, RestEndpoint } from '@data-client/rest';
export class Ticker extends Entity {
product_id = '';
price = 0;
pk() {
return this.product_id;
}
static key = 'Ticker';
static schema = { price: Number };
}
export const getTicker = new RestEndpoint({
urlPrefix: 'https://api.exchange.coinbase.com',
path: '/products/:productId/ticker',
schema: Ticker,
process(value, { productId }) {
value.product_id = productId;
return value;
},
pollFrequency: 2000,
});
```
```html title="AssetRow.vue" {14-20}
<script setup lang="ts">
import { computed, useTemplateRef } from 'vue';
import { useElementVisibility } from '@vueuse/core';
import { useSuspense, useSubscription } from '@data-client/vue';
import NumberFlow from '@number-flow/vue';
import { getTicker } from './Ticker';
const props = defineProps<{ productId: string }>();
const ticker = await useSuspense(getTicker, () => ({
productId: props.productId,
}));
const el = useTemplateRef('el');
const isVisible = useElementVisibility(el);
// null args means don't subscribe
useSubscription(
getTicker,
computed(() =>
isVisible.value ? { productId: props.productId } : null,
),
);
</script>
<template>
<div ref="el" class="listItem">
<h4>{{ productId }}</h4>
<NumberFlow
class="value"
:value="ticker.price"
:format="{ style: 'currency', currency: 'USD' }"
/>
</div>
</template>
```
Passing `null` as the second argument turns the subscription off for this component. Updates continue while other
components subscribe to the same data.
[useElementVisibility()](https://vueuse.org/core/useElementVisibility/) from VueUse uses [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API), which is very performant. [Template refs](https://vuejs.org/guide/essentials/template-refs.html) give access to the
[DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) element.
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: 197k | 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: 197k | 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: 197k | Updated | Claude CodeCodex | Verified | Install |