Skip to content

world.subscribe(listener) ​

Calls your listener with the world immediately and again after every change. It returns a function that stops the calls.

subscribe(listener: (node: GuiNode) => void): () => void
js
const stop = world.subscribe((node) => draw(node));

Parameters ​

ParameterWhat it is
listenerThe callback that receives the newest world (named node in the callbacks) immediately and then after every change.

Returns ​

A stop() function that ends the calls of your listener and does no harm when called twice.

Usage ​

Draw the world at every change ​

Every view works this way. Your page never changes the world directly. It follows the world by rendering everything from node at each call.

js
const world = await connectToHost();

world.subscribe((node) => {
  title.textContent = node.name;
  status.textContent = node.now?.text ?? '';
  sendButton.disabled = !node.canSend;
});

Stop following ​

Keep the function returned by subscribe and call it when a part of your page goes away. In this example the view stops after three calls:

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

// A fake world whose number of visitors changes every second.
const library = {
	name: 'Library',
	data: { visitors: (time) => 10 + (Math.floor(time / 1000) % 5) },
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	// useWorld subscribes for you. Here we also call `subscribe` ourselves to see each call.
	const { world, error } = useWorld({ fake: { world: library } });
	const [lines, setLines] = useState([]);
	const [isStopped, setIsStopped] = useState(false);
	const isConnected = world !== null;

	useEffect(() => {
		if (!isConnected) return undefined;
		// `subscribe` calls the function at once with the world, then after every change.
		// It returns a function that stops it. This example stops after three calls.
		let calls = 0;
		const stop = world.subscribe((node) => {
			calls += 1;
			const line = `Call ${calls}: ${node.data.visitors} visitors`;
			setLines((before) => [...before, line]);
			if (calls === 3) {
				stop();
				setIsStopped(true);
			}
		});
		return stop;
		// Subscribe once, when the world arrives.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [isConnected]);

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<h2>{world.name}</h2>
			<ol>
				{lines.map((line) => <li key={line}>{line}</li>)}
			</ol>
			<p>{isStopped ? 'Stopped after 3 calls.' : ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world whose number of visitors changes every second.
const library = {
	name: 'Library',
	data: { visitors: (time) => 10 + (Math.floor(time / 1000) % 5) },
};

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

const title = document.createElement('h2');
const list = document.createElement('ol');
const note = document.createElement('p');
document.body.append(title, list, note);

// `subscribe` calls the function at once with the world, then after every change.
// It returns a function that stops it. This example stops after three calls.
let calls = 0;
const stop = world.subscribe((node) => {
	calls += 1;
	title.textContent = node.name;
	const line = document.createElement('li');
	line.textContent = `Call ${calls}: ${node.data.visitors} visitors`;
	list.append(line);
	if (calls === 3) {
		stop();
		note.textContent = 'Stopped after 3 calls.';
	}
});
Live, on a fake world
Open

The first call happens before subscribe returns. Each change brings a new call (here a new number of visitors every second).

In React ​

The useWorld hook calls subscribe for you and re-renders your component at every change. Call subscribe yourself only for work outside rendering. Do it in a useEffect that returns the stop function as the React tab above does.

Caveats ​

  • The first call happens inside subscribe. Create the elements that your listener fills before you subscribe.
  • Each call gets a new frozen world. Writing into it throws a TypeError. Keep what you need in your own variables.
  • Many things count as a change: a new message, a new value in data, a new now or a change in webapp such as the theme or the keyboard. Render the whole world each time instead of guessing what changed.
  • Keep your listener quick. A world that shows a camera changes many times a second. When only data changes the kit calls your listener at most about once per screen frame. Even at that rate a slow listener slows your page. For one value that changes fast, use onData.
  • A listener that throws can prevent the other listeners from receiving that change. Catch errors inside your listener.
  • You can subscribe more than once (for example once per part of your page) and each call has its own stop.

Troubleshooting ​

subscribe never fails and has no error code.

ProblemWhyWhat to do
The page shows the world as it was at the start.The view rendered world once after connectToHost. That object is the first world and never changes.Render from node inside subscribe.
A click handler sees old values.The handler kept a world from an earlier call.Read world.get() inside the handler.
The listener runs twice per change in React.You subscribe in an effect that runs again at every render.Subscribe once as in the React tab above or use the world returned by useWorld.

See also ​

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