useLive()
Async rendering of remotely triggered data mutations.
useSuspense() + useSubscription() in one hook.
useLive() is reactive to data mutations; rerendering only when necessary.
Usage
import { useLive } from '@data-client/react'; import NumberFlow from '@number-flow/react'; import { getTicker } from './Ticker'; function AssetPrice({ productId }: Props) { const ticker = useLive(getTicker, { productId }); return ( <dl className="stats"> <div> <dt>{productId}</dt> <dd> <NumberFlow value={ticker.price} format={{ style: 'currency', currency: 'USD' }} /> </dd> </div> </dl> ); } interface Props { productId: string; } render(<AssetPrice productId="BTC-USD" />);
Behavior
Use null as the second argument to any Data Client hook means "do nothing."
A RestEndpoint without path or search params takes {} in its place, like enabled ? {} : null.
// todo could be undefined if id is undefined
const todo = useLive(TodoResource.get, id ? { id } : null);
When using React Navigation, useLive() will trigger fetches on focus if the data is considered stale. useLive() will also sub/unsub with focus/unfocus respectively.
In a hidden <Activity>, useLive() unsubscribes. It subscribes
again when shown. Example
Types
- Type
- With Generics
function useLive(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema>;
function useLive<
E extends EndpointInterface<
FetchFunction,
Schema | undefined,
undefined
>,
Args extends readonly [...Parameters<E>] | readonly [null],
>(
endpoint: E,
...args: Args
): E['schema'] extends Exclude<Schema, null>
? Denormalize<E['schema']>
: ReturnType<E>;
Examples
Bitcoin Price (polling)
When our component with useLive is rendered, getTicker will fetch at pollFrequency
milliseconds.
Explore the nextjs example
Pause hidden tabs
Keep tabs mounted in <Activity>. Only the shown tab polls.
import React from 'react'; import AssetPrice from './AssetPrice'; const products = ['BTC-USD', 'ETH-USD', 'SOL-USD']; function Markets() { const [shown, setShown] = React.useState(products[0]); return ( <> <header className="appHeader"> <h1 className="appTitle">Markets</h1> <div className="segmented" role="group" aria-label="Product"> {products.map(productId => ( <button key={productId} aria-pressed={productId === shown} onClick={() => setShown(productId)} > {productId.split('-')[0]} </button> ))} </div> </header> {products.map(productId => ( <React.Activity key={productId} mode={productId === shown ? 'visible' : 'hidden'} > <AssetPrice productId={productId} /> </React.Activity> ))} </> ); } render(<Markets />);
A hidden tab keeps its state, but its Effects stop. If no other component subscribes to its price, polling stops. When shown, polling resumes. If the last fetch is older than pollFrequency, it fetches at once.
Hidden tabs still render, so every tab fetches its price before it shows. Switching tabs shows a price with no loading state.