# useSubscription()

Keeps data that changes often up to date.

The default [polling subscriptions](https://dataclient.io/vue/api/PollingSubscription.md) need
[pollFrequency](https://dataclient.io/rest/api/RestEndpoint.md#pollfrequency) set on the [Endpoint](https://dataclient.io/rest/api/Endpoint.md). Without it, subscribing
logs an error and does nothing.

> **Tip**
>
> [useLive()](https://dataclient.io/vue/api/useLive.md) combines `useSubscription()` with [useSuspense()](https://dataclient.io/vue/api/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.md) 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.
