Skip to main content

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.

tip

useLive() is a terser way to use in combination with useSuspense(),

Usage

api/Price
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,
});
MasterPrice
import { useSuspense, useSubscription } from '@data-client/react';
import { getPrice } from 'api/Price';

function MasterPrice({ symbol }: { symbol: string }) {
const price = useSuspense(getPrice, { symbol });
useSubscription(getPrice, { symbol });
// ...
}

Behavior

Conditional Dependencies

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

When using React Navigation, useSubscription() will sub/unsub with focus/unfocus respectively.

Types

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

Examples

Only subscribe while element is visible

MasterPrice.tsx
import { useSuspense, useSubscription } from '@data-client/react';
import { getPrice } from 'api/Price';

function MasterPrice({ symbol }: { symbol: string }) {
const price = useSuspense(getPrice, { symbol });
const [ref, entry] = useIntersectionObserver();
// null params means don't subscribe
useSubscription(getPrice, entry?.isIntersecting ? null : { symbol });

return (
<div ref={ref}>{price.value.toLocaleString('en', { currency: 'USD' })}</div>
);
}

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.

useIntersectionObserver() uses IntersectionObserver, which is very performant. ref allows us to access the DOM.

Crypto prices (websockets)

We implemented our own StreamManager to handle our custom websocket protocol. Here we listen to the subcribe/unsubcribe actions sent by useSubscription to ensure we only listen to updates for components that are rendered.

More Demos