useLive()
- 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>;
Fetch and use data, while keeping it updated with remote changes.
useSuspense() + useSubscription() in one hook.
Conditional Dependencies
Use null
as the second argument on any rest hooks 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.
Example
▶api/ExchangeRates.ts
▶ProfileList.tsx
import { useLive } from '@rest-hooks/react';import { getExchangeRates } from './api/ExchangeRates';function AssetPrice({ symbol }: Props) {const { data: price } = useLive(getExchangeRates, {currency: 'USD',});const displayPrice = new Intl.NumberFormat('en-US', {style: 'currency',currency: 'USD',}).format(1 / Number.parseFloat(price.rates[symbol]));return (<span>{symbol} {displayPrice}</span>);}interface Props {symbol: string;}render(<AssetPrice symbol="BTC" />);