Skip to main content

useLive()

Async rendering of frequently changing remote data.

useSuspense() + useSubscription() in one hook.

Usage

import { Entity, RestEndpoint } from '@data-client/rest';

export class ExchangeRates extends Entity {
  currency = 'USD';
  rates: Record<string, number> = {};

  pk(): string {
    return this.currency;
  }
  static key = 'ExchangeRates';

  static schema = {
    rates: new schema.Values(FloatSerializer),
  };
}

export const getExchangeRates = new RestEndpoint({
  urlPrefix: 'https://www.coinbase.com/api/v2',
  path: '/exchange-rates',
  searchParams: {} as { currency: string },
  schema: { data: ExchangeRates },
  pollFrequency: 15000,
});
import { useLive } from '@data-client/react';
import { getExchangeRates } from './ExchangeRates';

function AssetPrice({ symbol }: Props) {
  const currency = 'USD';
  const { data: price } = useLive(getExchangeRates, { currency });
  return (
    <center>
      {symbol}{' '}
      <Formatted value={1 / price.rates[symbol]} formatter="currency" />
    </center>
  );
}
interface Props {
  symbol: string;
}
render(<AssetPrice symbol="BTC" />);
Live Preview
Loading...
Store

Behavior

Conditional Dependencies

Use null as the second argument on any reactive data client to indicate "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

Explore more Reactive Data Client demos