useSubscription()
Great for keeping resources up-to-date with frequent changes.
When using the default polling subscriptions, frequency must be set in Endpoint, otherwise will have no effect.
useLive() is a terser way to use in combination with useSuspense(),
Usage
import { Resource, Entity } from '@data-client/rest';
export class Price extends Entity {
symbol = '';
price = '0.0';
// ...
pk() {
return this.symbol;
}
}
export const getPrice = new RestEndpont({
urlPrefix: 'http://test.com',
path: '/price/:symbol',
schema: Price,
pollFrequency: 5000,
});
<script setup lang="ts">
import { useSuspense, useSubscription } from '@data-client/vue';
import { getPrice } from 'api/Price';
const props = defineProps<{ symbol: string }>();
const price = await useSuspense(getPrice, { symbol: props.symbol });
useSubscription(getPrice, { symbol: props.symbol });
// ...
</script>
Behavior
Use null as the second argument to any Data Client hook means "do nothing."
// 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 or refs (including computed).
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 { getPrice } from 'api/Price';
const props = defineProps<{ symbol: string }>();
const price = await useSuspense(getPrice, { symbol: props.symbol });
const el = useTemplateRef('el');
const isVisible = useElementVisibility(el);
// null params means don't subscribe
useSubscription(
getPrice,
computed(() => (isVisible.value ? { symbol: props.symbol } : null)),
);
</script>
<template>
<div ref="el">{{ price.price }}</div>
</template>
When null is send as the second argument, the subscription is deactivated. Of course,
if other components are still subscribed the data updates will still be active.
useElementVisibility() from VueUse uses IntersectionObserver, which is very performant. Template refs allow us to access the DOM.