useSubscription()
Keeps data that changes often up to date.
The default polling subscriptions need pollFrequency set on the Endpoint. Without it, subscribing logs an error and does nothing.
useLive() combines useSubscription() with useSuspense() in one call.
Usage
<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
Use null as the second argument to any Data Client hook means "do nothing."
A RestEndpoint without path or search params takes {} in its place, like enabled ? {} : null.
// 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 changes, the previous subscription is removed and a new one is created for the new arguments.
Types
function useSubscription(
endpoint: ReadEndpoint,
...args: MaybeRefsOrGetters<Parameters<typeof endpoint>> | [null]
): void;
Arguments can be plain values, refs (including 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
<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() from VueUse uses IntersectionObserver, which is very performant. Template refs give access to the DOM element.