Skip to content

Load older messages ​

At first messages holds only the recent part of the conversation. A Load older messages button above the first message calls loadMore() to fetch the rest. When a press adds no messages, the note This is the start of the conversation. takes the place of the button. In the example the first press already reaches the start because a fake agent keeps no older messages.

jsx
import { useLayoutEffect, useRef, useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake agent to build with. Since it keeps no older messages, loadMore() finds none.
const diary = {
	name: 'Diary',
	onMessage: (message) => `Noted: ${message.text}`,
};

export default function App() {
	// While building: the fake agent. In the webapp: useWorld()
	const { world: agent, error } = useWorld({ fake: { agent: diary } });
	const [isLoading, setIsLoading] = useState(false);
	const [isAtStart, setIsAtStart] = useState(false); // true once there is nothing older
	// The messages scroll inside their own box, and the distance of the scroll position
	// from its bottom is kept while older messages arrive at the top.
	const box = useRef(null);
	const keptFromBottom = useRef(null);
	const count = agent ? agent.messages.length : 0;
	useLayoutEffect(() => {
		// After React draws the older messages, scroll back to the same distance from the bottom.
		if (keptFromBottom.current !== null && box.current) {
			box.current.scrollTop = box.current.scrollHeight - keptFromBottom.current;
			keptFromBottom.current = null;
		}
	}, [count]);

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!agent) return <p>Connecting…</p>;

	async function loadOlder() {
		setIsLoading(true);
		// Older messages go on top: keep the distance from the bottom, so that what the person reads stays put.
		keptFromBottom.current = box.current.scrollHeight - box.current.scrollTop;
		// loadMore() adds older messages at the start of `messages`, and says how many.
		const added = await agent.loadMore();
		setIsLoading(false);
		if (added === 0) {
			keptFromBottom.current = null;
			setIsAtStart(true);
		}
	}

	return (
		<>
			{isAtStart ? (
				<p><i>This is the start of the conversation.</i></p>
			) : (
				<button onClick={loadOlder} disabled={isLoading}>{isLoading ? 'Loading…' : 'Load older messages'}</button>
			)}
			<div ref={box} style={{ maxHeight: 160, overflowY: 'auto' }}>
				{agent.messages.map((message) => (
					<p key={message.id}><b>{message.fromMe ? 'You' : message.from}:</b> {message.text}</p>
				))}
			</div>
			<button onClick={() => agent.send('Fed the cat')} disabled={!agent.canSend}>Write "Fed the cat"</button>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake agent to build with. Since it keeps no older messages, loadMore() finds none.
const diary = {
	name: 'Diary',
	onMessage: (message) => `Noted: ${message.text}`,
};

// While building: the fake agent. In the webapp: const agent = await connectToHost();
const agent = await connectToHost({ fake: { agent: diary } });

const olderButton = document.createElement('button');
olderButton.textContent = 'Load older messages';
// The messages scroll inside their own box.
const list = document.createElement('div');
list.style.cssText = 'max-height: 160px; overflow-y: auto';
const writeButton = document.createElement('button');
writeButton.textContent = 'Write "Fed the cat"';
writeButton.onclick = () => agent.send('Fed the cat');
document.body.append(olderButton, list, writeButton);

// The distance of the scroll position from the bottom of the box, kept while older messages arrive.
let keptFromBottom = null;

olderButton.onclick = async () => {
	olderButton.disabled = true;
	olderButton.textContent = 'Loading…';
	// Older messages go on top: keep the distance from the bottom, so that what the person reads stays put.
	keptFromBottom = list.scrollHeight - list.scrollTop;
	// loadMore() adds older messages at the start of `messages`, and says how many.
	const added = await agent.loadMore();
	if (added === 0) keptFromBottom = null;
	olderButton.disabled = false;
	olderButton.textContent = 'Load older messages';
	if (added === 0) {
		// When there is nothing older, say so in place of the button.
		const start = document.createElement('p');
		const words = document.createElement('i');
		words.textContent = 'This is the start of the conversation.';
		start.append(words);
		olderButton.replaceWith(start);
	}
};

agent.subscribe((node) => {
	writeButton.disabled = !node.canSend;
	list.replaceChildren(...node.messages.map((message) => {
		const line = document.createElement('p');
		const sender = document.createElement('b');
		sender.textContent = `${message.fromMe ? 'You' : message.from}:`;
		line.append(sender, ` ${message.text ?? ''}`);
		return line;
	}));
	// After drawing the older messages, scroll back to the same distance from the bottom.
	if (keptFromBottom !== null) {
		list.scrollTop = list.scrollHeight - keptFromBottom;
		keptFromBottom = null;
	}
});
Live, on a fake world
Open

How it works ​

await world.loadMore() adds the older messages at the start of messages in the same oldest-first order and resolves with the number it added (0 when none are left). Your view renders them like any other change because subscribe calls its listener again (in React the component that calls useWorld re-renders). The example disables the button while loadMore runs so that a double click does not load the same messages twice. Before the call it stores the distance of the scroll position from the bottom of the message box. After drawing the older messages at the top it scrolls back to that distance to keep in place what the person was reading. loadMore only reads and sends nothing to the world on behalf of the person.

See also ​

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.