useHistory

The useHistory hook reads the channel's history backwards from the point where the channel attached, one page at a time, and keeps the deliveries it has read in one list, oldest first. It reads the first page when the transport is available, and loadMore reads the next older page.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

import { useHistory } from '@ably/ai-transport/react';

function Earlier() {
  const { items, hasNext, loading, loadMore } = useHistory({ limit: 50 });

  return (
    <>
      {hasNext && <button onClick={loadMore} disabled={loading}>Load older</button>}
      <Messages deliveries={items} />
    </>
  );
}

This hook must be used within a TransportProvider.

Reading history attaches the channel. The list starts again when the provider creates a new transport.

Parameters

limitrequiredNumber
Messages per page. A change takes effect when the provider creates a new transport.
channelNameoptionalString
The channel name of the provider to read. Omit it to read the nearest provider.

The hook throws an ErrorInfo with InvalidArgument when no matching TransportProvider encloses the component.

Returns

itemsDelivery
Every delivery read so far, oldest first. Each loadMore adds an older page to the front.
hasNextBoolean
Whether an older page exists. true until a page reports the end of history.
loadingBoolean
Whether a page is being read.
errorErrorInfo or undefined
The error the last read failed with, or undefined.
loadMore() => Promise<void>
Read the next older page.

Load an older page

loadMore(): Promise<void>

Read the next older page and add it to the front of items. The promise resolves once the page is in items. A call while a page is loading, or after the end of history, does nothing. A failed read sets error.

Example

A conversation view loads older messages when the user scrolls to the top.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

import { useHistory } from '@ably/ai-transport/react';

function ConversationHistory() {
  const { items, hasNext, loading, error, loadMore } = useHistory({ limit: 30 });

  const onScroll = (e) => {
    if (e.currentTarget.scrollTop === 0 && hasNext && !loading) void loadMore();
  };

  if (error) return <p>Could not load history: {error.message}</p>;

  return (
    <div onScroll={onScroll} style={{ overflowY: 'auto', height: 400 }}>
      {items.map(({ message, event }, i) => (event ? <Row key={`${message.serial}-${i}`} event={event} /> : null))}
    </div>
  );
}