useWorld
useWorld is the React hook that every React example and component of this site imports. It calls connectToHost once when the component mounts and re-renders the component at every change of the world. Copy it into your project before you copy any example or component.
The hook
Save this file as useWorld.js next to your components:
js
// useWorld.js: copy this file next to your React components.
// It connects your view to the world it is for and keeps your component up
// to date by rendering it again at every change of the world.
import { useEffect, useState } from 'react';
import { connectToHost } from '@unaiverse/gui-kit';
/**
* Gives a React component the world its view is for.
*
* - `world` is null until the world arrives, then the newest world after every change.
* - `error` holds the error when the view cannot connect (its `code` says why, for example 'no-host').
*
* Pass `{ fake: { world: { ... } } }` while you build (no account, no network),
* and nothing in the webapp.
*
* @param {object} [options] - What `connectToHost` takes, for example `{ fake: { world } }`.
* @returns {{ world: object | null, error: Error | null }}
*/
export function useWorld(options) {
const [state, setState] = useState({ world: null, error: null });
useEffect(() => {
let isActive = true;
let stop = () => {};
connectToHost(options)
.then((world) => {
if (!isActive) return;
// Called at once, then after every change of the world.
stop = world.subscribe((next) => setState({ world: next, error: null }));
})
.catch((error) => {
if (isActive) setState({ world: null, error });
});
return () => {
isActive = false;
stop();
};
// Connect once, when the component appears.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return state;
}Use it
A component that calls useWorld() handles the three states of every view: (1) the connection failed, (2) the view is connecting and (3) the world has arrived.
jsx
import { useWorld } from './useWorld.js';
// A fake world to build with: no account, no network.
const library = {
name: 'Library',
now: { text: 'Open until 18:00' },
data: { visitors: (time) => 10 + (Math.floor(time / 1000) % 5) },
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: library } });
// The three states of every view: it failed, it is connecting, it is here.
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<>
<h2>{world.name}</h2>
<p>{world.now?.text}</p>
<p>Visitors now: {world.data.visitors}</p>
</>
);
}js
import { connectToHost } from '@unaiverse/gui-kit';
// A fake world to build with: no account, no network.
const library = {
name: 'Library',
now: { text: 'Open until 18:00' },
data: { visitors: (time) => 10 + (Math.floor(time / 1000) % 5) },
};
const status = document.createElement('p');
status.textContent = 'Connecting…';
const title = document.createElement('h2');
const now = document.createElement('p');
const visitors = document.createElement('p');
document.body.append(status, title, now, visitors);
try {
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: library } });
status.remove();
// Called at once, then after every change of the world.
world.subscribe((node) => {
title.textContent = node.name;
now.textContent = node.now?.text ?? '';
visitors.textContent = `Visitors now: ${node.data.visitors}`;
});
} catch (error) {
status.textContent = `Could not connect (${error.code}).`;
}The JavaScript tab builds the same view without React from connectToHost and world.subscribe.
Returns
| Field | What it is |
|---|---|
world | null until the world arrives and then the newest world after every change. |
error | null or the error that stopped the connection. Its code is 'no-host' or 'unsupported' (connectToHost › Troubleshooting). |
Parameters
| Parameter | What it is |
|---|---|
options | The options of connectToHost ({ fake: { world: { ... } } } while you build and none in the webapp). |
Change it
- One world for many components: call
useWorld()once in your top component and passworlddown as a prop. Each call opens a connection of its own and the webapp ends the earlier one when a new one starts. - Your own loading screen: replace the
Connecting…line (Show a loading screen). - Strict mode: in development React runs the effect twice. The hook needs no change because the cleanup of the first run discards its connection and the webapp ends that connection when the second one starts.