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 {
readonly symbol: string | undefined = undefined;
readonly price: string = '0.0';
// ...
pk() {
return this.symbol;
}
}
export const getPrice = new RestEndpont({
urlPrefix: 'http://test.com',
path: '/price/:symbol',
schema: Price,
pollFrequency: 5000,
});
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
Use null
as the second argument to any RDC hook means "do nothing."
// todo could be undefined if id is undefined
const todo = useSubscription(TodoResource.get, id ? { id } : null);
When using React Navigation, useSubscription() will sub/unsub with focus/unfocus respectively.
Types
- Type
- With Generics
function useSubscription(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): void;
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
import { useRef } from 'react';
import { useSuspense, useSubscription } from '@data-client/react';
import { getPrice } from 'api/Price';
function MasterPrice({ symbol }: { symbol: string }) {
const price = useSuspense(getPrice, { symbol });
const ref = useRef();
const onScreen = useOnScreen(ref);
// null params means don't subscribe
useSubscription(getPrice, onScreen ? null : { symbol });
return (
<div ref={ref}>{price.value.toLocaleString('en', { currency: 'USD' })}</div>
);
}
Using the last argument active
we control whether the subscription is active or not
based on whether the element rendered is visible on screen.
useOnScreen() uses IntersectionObserver, which is very performant. useRef 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.