# useSubscription()

Keeps data that changes often up to date.

The default [polling subscriptions](https://dataclient.io/docs/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/docs/api/useLive.md) combines `useSubscription()` with [useSuspense()](https://dataclient.io/docs/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,
});
```

```tsx title="AssetPrice" {7}
import { useSuspense, useSubscription } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { getTicker } from './Ticker';

function AssetPrice({ productId }: { productId: string }) {
  const ticker = useSuspense(getTicker, { productId });
  useSubscription(getTicker, { productId });
  return (
    <dl className="stats">
      <div>
        <dt>{productId}</dt>
        <dd>
          <NumberFlow
            value={ticker.price}
            format={{ style: 'currency', currency: 'USD' }}
          />
        </dd>
      </div>
    </dl>
  );
}
render(<AssetPrice productId="BTC-USD" />);
```

## 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, id ? { id } : null);
> ```

> **Info: React Native**
>
> When using React Navigation, useSubscription() will sub/unsub with focus/unfocus respectively.

In a hidden [`<Activity>`](https://react.dev/reference/react/Activity), `useSubscription()` unsubscribes. It
subscribes again when shown. [Example](#pause-while-hidden)

## Types

```typescript
function useSubscription(
  endpoint: ReadEndpoint,
  ...args: Parameters<typeof endpoint> | [null]
): void;
```

```typescript
function useSubscription<
  E extends EndpointInterface<
    FetchFunction,
    Schema | undefined,
    undefined
  >,
  Args extends readonly [...Parameters<E>] | readonly [null],
>(endpoint: E, ...args: Args): void;
```

## 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,
});
```

```tsx title="useInView"
import React from 'react';

/** Whether the element is on screen */
export function useInView<T extends Element>() {
  const ref = React.useRef<T>(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    // one callback can hold several entries: the last is current
    const observer = new IntersectionObserver(entries =>
      entries.forEach(entry => setInView(entry.isIntersecting)),
    );
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);
  return [ref, inView] as const;
}
```

```tsx title="Watchlist" {9-10}
import { useSuspense, useSubscription } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { getTicker } from './Ticker';
import { useInView } from './useInView';

function AssetRow({ productId }: { productId: string }) {
  const ticker = useSuspense(getTicker, { productId });
  const [ref, inView] = useInView<HTMLDivElement>();
  // null args means don't subscribe
  useSubscription(getTicker, inView ? { productId } : null);
  return (
    <div className="listItem" ref={ref}>
      <h4>{productId}</h4>
      <NumberFlow
        className="value"
        value={ticker.price}
        format={{ style: 'currency', currency: 'USD' }}
      />
    </div>
  );
}

const products = [
  'BTC-USD',
  'ETH-USD',
  'SOL-USD',
  'BCH-USD',
  'LTC-USD',
  'AAVE-USD',
  'AVAX-USD',
  'LINK-USD',
];
render(
  <>
    <header className="appHeader">
      <h1 className="appTitle">Watchlist</h1>
    </header>
    <div className="list scroll">
      {products.map(productId => (
        <AssetRow key={productId} productId={productId} />
      ))}
    </div>
  </>,
);
```

Passing `null` as the second argument turns the subscription off for this component. Updates continue while other
components subscribe to the same data.

`useInView()` uses [IntersectionObserver](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API),
which is very performant. Hooks such as [useIntersectionObserver()](https://usehooks.com/useintersectionobserver) do
the same.

### Pause while hidden

To hide a panel or tab, wrap it in [`<Activity>`](https://react.dev/reference/react/Activity). `AssetPrice` needs
no change.

```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,
});
```

```tsx title="AssetPrice"
import { useSuspense, useSubscription } from '@data-client/react';
import NumberFlow from '@number-flow/react';
import { getTicker } from './Ticker';

export default function AssetPrice({ productId }: { productId: string }) {
  const ticker = useSuspense(getTicker, { productId });
  useSubscription(getTicker, { productId });
  return (
    <dl className="stats">
      <div>
        <dt>{productId}</dt>
        <dd>
          <NumberFlow
            value={ticker.price}
            format={{ style: 'currency', currency: 'USD' }}
          />
        </dd>
      </div>
    </dl>
  );
}
```

```tsx title="PricePanel" {14-16}
import React from 'react';
import AssetPrice from './AssetPrice';

function PricePanel({ productId }: { productId: string }) {
  const [open, setOpen] = React.useState(false);
  return (
    <>
      <header className="appHeader">
        <h1 className="appTitle">Prices</h1>
        <button aria-expanded={open} onClick={() => setOpen(!open)}>
          {open ? 'Hide' : 'Show'} price
        </button>
      </header>
      <React.Activity mode={open ? 'visible' : 'hidden'}>
        <AssetPrice productId={productId} />
      </React.Activity>
    </>
  );
}
render(<PricePanel productId="BTC-USD" />);
```

A hidden `<Activity>` keeps `AssetPrice` and its state, but stops its Effects. If no other component subscribes to the
price, polling stops. When shown, polling resumes. If the last fetch is older than
[pollFrequency](https://dataclient.io/rest/api/RestEndpoint.md#pollfrequency), it fetches at once.

A hidden `<Activity>` still renders. So `useSuspense()` fetches the price before the panel opens, and the panel opens
without a loading state.

### Crypto prices (websockets)

A custom `StreamManager` handles the websocket protocol. It listens to the [subscribe and unsubscribe
actions](https://dataclient.io/docs/api/Actions.md#subscribe) that `useSubscription()` sends, so it only receives updates for rendered components.

Example app: [coin-app](https://github.com/reactive/data-client/tree/master/examples/coin-app) ([`src/resources/StreamManager.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/resources/StreamManager.ts), [`src/resources/Ticker.ts`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/resources/Ticker.ts), [`src/pages/Home/AssetPrice.tsx`](https://github.com/reactive/data-client/blob/master/examples/coin-app/src/pages/Home/AssetPrice.tsx))
