Skip to content

LoadingAndErrors ​

Between the start of your view and the arrival of the world there is a short connection phase. Sometimes the world never arrives because the page was opened directly in a browser tab instead of inside the webapp or because the webapp does not accept the version of the kit in your view. LoadingAndErrors shows "Connecting…" while the Promise of connectToHost is pending. When the Promise rejects it shows the cause and a way to recover. Once the world is there it renders your view. Put it around your whole view.

jsx
import { useWorld } from './useWorld.js';

// The component: copy this part.

/** What the person reads when the view cannot connect, for each error code. */
const CONNECT_PROBLEMS = {
	'no-host': {
		title: 'This view opens inside UNaIVERSE',
		text: 'Open it from its world, in the UNaIVERSE webapp. If you are there already, the webapp did not answer: try again.',
	},
	unsupported: { title: 'This view needs an update', text: 'The webapp and this view do not speak the same version. Try again later.' },
};

/**
 * LoadingAndErrors: what the person sees before the world arrives and when it
 * cannot arrive, either a "Connecting…" line or the reason in words with a way out.
 * Once the world is here, it draws its children, your view.
 * @param {object} props
 * @param {object|null} props.world - The world, from useWorld (null until it arrives).
 * @param {Error|null} props.error - The error, from useWorld (null when there is none).
 * @param {string} [props.worldUrl] - The address of the world in UNaIVERSE, for a link when the view is opened alone.
 * @param {React.ReactNode} props.children - Your view, drawn once the world is here.
 */
export function LoadingAndErrors({ world, error, worldUrl, children }) {
	const box = { display: 'grid', gap: 8, justifyItems: 'start', padding: 16, borderRadius: 14, border: '1px solid rgba(127, 127, 127, 0.3)' };
	if (error) {
		const problem = CONNECT_PROBLEMS[error.code] ?? { title: 'Could not connect', text: error.message };
		return (
			<div role="alert" style={box}>
				<strong>{problem.title}</strong>
				<span style={{ fontSize: 14, opacity: 0.8 }}>{problem.text}</span>
				<div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
					{error.code === 'no-host' && worldUrl && <a href={worldUrl}>Open it in UNaIVERSE</a>}
					{/* Connecting again is loading the page again. */}
					<button type="button" onClick={() => window.location.reload()}>Try again</button>
				</div>
			</div>
		);
	}
	if (!world) {
		return (
			<div role="status" style={box}>
				{/* A progress bar with no value, which the browser shows as busy. */}
				<progress aria-label="Connecting" style={{ width: 160 }} />
				<span>Connecting…</span>
			</div>
		);
	}
	return children;
}

// Using it, on a fake world.

// A fake world to build with: no account, no network.
const arena = { name: 'Arena', now: { text: 'Waiting for players' } };

/** Your view: its own component, drawn only once the world is here. */
function ArenaView({ world }) {
	return <p style={{ margin: 0 }}>Welcome to {world.name}. {world.now?.text}.</p>;
}

/** The error a view gets when it is opened alone, outside the webapp. */
const OUTSIDE = Object.assign(new Error('This view is not inside the UNaIVERSE webapp'), { code: 'no-host' });

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: arena } });

	// The three things a person can see. The first two pretend, and the last one is the real connection.
	return (
		<div style={{ display: 'grid', gap: 12, maxWidth: 480 }}>
			<LoadingAndErrors world={null} error={null} />
			<LoadingAndErrors world={null} error={OUTSIDE} worldUrl="https://unaiverse.io" />
			<LoadingAndErrors world={world} error={error}>
				<ArenaView world={world} />
			</LoadingAndErrors>
		</div>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/** What the person reads when the view cannot connect, for each error code. */
const CONNECT_PROBLEMS = {
	'no-host': {
		title: 'This view opens inside UNaIVERSE',
		text: 'Open it from its world, in the UNaIVERSE webapp. If you are there already, the webapp did not answer: try again.',
	},
	unsupported: { title: 'This view needs an update', text: 'The webapp and this view do not speak the same version. Try again later.' },
};

/**
 * Shows in `container` what the person sees before the world arrives and when it
 * cannot arrive, either a "Connecting…" line or the reason in words with a way
 * out. Unlike the other components, it runs before there is a world and therefore
 * takes the connection itself, the promise that `connectToHost()` returns.
 * @param {HTMLElement} container - Where to draw it.
 * @param {Promise<object>} connecting - The connection, from connectToHost.
 * @param {{worldUrl?: string}} [options] - The address of the world in UNaIVERSE, for a link when the view is opened alone.
 * @returns {Promise<object>} The world, once it is here (it then removes what it drew). When the
 *   connection fails, it shows why and never resolves, to keep the code after it from running.
 */
export function loadingAndErrors(container, connecting, { worldUrl } = {}) {
	const box = document.createElement('div');
	box.setAttribute('role', 'status');
	Object.assign(box.style, { display: 'grid', gap: '8px', justifyItems: 'start', padding: '16px', borderRadius: '14px', border: '1px solid rgba(127, 127, 127, 0.3)' });
	// A progress bar with no value, which the browser shows as busy.
	const progress = document.createElement('progress');
	progress.setAttribute('aria-label', 'Connecting');
	progress.style.width = '160px';
	const words = document.createElement('span');
	words.textContent = 'Connecting…';
	box.append(progress, words);
	container.append(box);

	const showProblem = (error) => {
		const problem = CONNECT_PROBLEMS[error.code] ?? { title: 'Could not connect', text: error.message };
		box.setAttribute('role', 'alert');
		const title = document.createElement('strong');
		title.textContent = problem.title;
		const text = document.createElement('span');
		text.textContent = problem.text;
		Object.assign(text.style, { fontSize: '14px', opacity: '0.8' });
		const row = document.createElement('div');
		Object.assign(row.style, { display: 'flex', alignItems: 'center', gap: '12px' });
		if (error.code === 'no-host' && worldUrl) {
			const link = document.createElement('a');
			link.href = worldUrl;
			link.textContent = 'Open it in UNaIVERSE';
			row.append(link);
		}
		// Connecting again is loading the page again.
		const again = document.createElement('button');
		again.type = 'button';
		again.textContent = 'Try again';
		again.onclick = () => window.location.reload();
		row.append(again);
		box.replaceChildren(title, text, row);
	};

	return connecting.then(
		(world) => {
			box.remove();
			return world;
		},
		(error) => {
			showProblem(error);
			return new Promise(() => {});
		},
	);
}

// Using it, on a fake world.

// A fake world to build with: no account, no network.
const arena = { name: 'Arena', now: { text: 'Waiting for players' } };

/** The error a view gets when it is opened alone, outside the webapp. */
const OUTSIDE = Object.assign(new Error('This view is not inside the UNaIVERSE webapp'), { code: 'no-host' });

// The three things a person can see. The first two pretend, and the last one is the real connection.
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', maxWidth: '480px' });
const [connectingBox, outsideBox, worldBox] = [1, 2, 3].map(() => document.createElement('div'));
page.append(connectingBox, outsideBox, worldBox);
document.body.append(page);

loadingAndErrors(connectingBox, new Promise(() => {}));
loadingAndErrors(outsideBox, Promise.reject(OUTSIDE), { worldUrl: 'https://unaiverse.io' });

// While building: the fake world. In the webapp: loadingAndErrors(worldBox, connectToHost())
const world = await loadingAndErrors(worldBox, connectToHost({ fake: { world: arena } }));

// Your view, drawn only once the world is here.
const welcome = document.createElement('p');
welcome.style.margin = '0';
worldBox.append(welcome);
world.subscribe((node) => {
	welcome.textContent = `Welcome to ${node.name}. ${node.now?.text}.`;
});
Live, on a fake world
Open

The example stacks the three states a person can see: (1) a connection that never ends, (2) the error shown when the page is opened outside the webapp (both simulated) and (3) the real connection to the fake world.

connectToHost() rejects with an error whose code gives the cause (useWorld returns the same error as error):

CodeWhenWhat the person reads
'no-host'The page is not inside the webapp (opened directly in a browser tab) or the webapp did not answer in time.This view opens inside UNaIVERSE (with a link to the world when you pass worldUrl).
'unsupported'The webapp does not accept the version of your kit.This view needs an update.

Any other error shows Could not connect with the message of the error. Try again reloads the page and therefore starts the connection again (Errors and the person's controls and connectToHost).

In React put your view in a component of its own inside LoadingAndErrors (ArenaView in the example). LoadingAndErrors renders its children only after the world has arrived and your view therefore never receives a null world.

Props ​

PropDefaultWhat it is
world(required)The world from useWorld (null until it arrives).
error(required)The error from useWorld (null when there is none).
worldUrlnoneThe address of the world in UNaIVERSE. A page opened outside the webapp shows a link to it.
childrenYour view. LoadingAndErrors renders it only after the world has arrived.

Parameters ​

The other components take the world as an argument. loadingAndErrors(container, connecting, options) instead runs before the world exists and takes the pending connection:

js
const world = await loadingAndErrors(document.body, connectToHost());
ParameterWhat it is
containerThe element to render into.
connectingThe Promise returned by connectToHost().
options.worldUrlThe address of the world in UNaIVERSE for the link shown when the page is opened outside the webapp.

It returns a Promise. When the connection succeeds the component removes what it rendered and the Promise resolves with the world. On a failed connection it shows the cause and the Promise never resolves to keep the code after the await from running.

Change it ​

  • Show your own loading screen with your logo or a skeleton of your view in place of the progress bar (Show a loading screen).
  • Make the page useful outside the webapp. For 'no-host' render a public page of yours (what the world is, how to join it) in place of the message (Show a message outside the webapp).
  • Handle the end of the world. After the connection world.status can become 'ended' or 'unreachable' and WorldStatus shows it.

See also ​

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