Skip to main content

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 { Entity, RestEndpoint } from '@data-client/rest';

export class Ticker extends Entity {
  product_id = '';
  trade_id = 0;
  price = 0;
  size = '0';
  time = Temporal.Instant.fromEpochSeconds(0);
  bid = '0';
  ask = '0';
  volume = '';

  pk(): string {
    return this.product_id;
  }
  static key = 'Ticker';

  static schema = {
    price: Number,
    time: Temporal.Instant.from,
  };
}

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,
});
import { useLive } from '@data-client/react';
import { getTicker } from './Ticker';

function AssetPrice({ productId }: Props) {
  const ticker = useLive(getTicker, { productId });
  return (
    <center>
      {productId}{' '}
      <Formatted value={ticker.price} formatter="currency" />
    </center>
  );
}
interface Props {
  productId: string;
}
render(<AssetPrice productId="BTC-USD" />);
🔴 Live Preview
Store

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 = useLive(TodoResource.get, id ? { id } : null);
React Native

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.

Types

function useLive(
endpoint: ReadEndpoint,
...args: Parameters<typeof endpoint> | [null]
): Denormalize<typeof endpoint.schema>;

Examples

Bitcoin Price (polling)

When our component with useLive is rendered, getTicker will fetch at pollFrequency miliseconds.

More Demos