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.
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
limitrequiredNumberchannelNameoptionalStringThe hook throws an ErrorInfo with InvalidArgument when no matching TransportProvider encloses the component.
Returns
itemsDeliveryloadMore adds an older page to the front.hasNextBooleantrue until a page reports the end of history.loadingBooleanerrorErrorInfo or undefinedundefined.loadMore() => Promise<void>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.
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>
);
}