useWorld
useWorld è l'hook React che importano tutti gli esempi e i componenti React di questo sito. Chiama connectToHost una volta quando il componente viene montato e fa il re-render del componente a ogni cambiamento del mondo. Copialo nel tuo progetto prima di copiare qualsiasi esempio o componente.
L'hook
Salva questo file come useWorld.js accanto ai tuoi componenti:
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;
}Usalo
Un componente che chiama useWorld() gestisce i tre stati di ogni vista: (1) la connessione è fallita, (2) la vista si sta connettendo e (3) il mondo è arrivato.
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}).`;
}La scheda JavaScript costruisce la stessa vista senza React a partire da connectToHost e world.subscribe.
Valore restituito
| Campo | Che cos'è |
|---|---|
world | null finché il mondo non arriva e poi il mondo più recente dopo ogni cambiamento. |
error | null o l'errore che ha fermato la connessione. Il suo code è 'no-host' o 'unsupported' (connectToHost › Risoluzione dei problemi). |
Parametri
| Parametro | Che cos'è |
|---|---|
options | Le opzioni di connectToHost ({ fake: { world: { ... } } } durante lo sviluppo e nessuna nella webapp). |
Modificalo
- Un mondo per molti componenti: chiama
useWorld()una volta nel componente più in alto e passaworldin giù come prop. Ogni chiamata apre una sua connessione e quando ne parte una nuova la webapp chiude quella precedente. - Una tua schermata di caricamento: sostituisci la riga
Connecting…(Mostra una schermata di caricamento). - Strict mode: durante lo sviluppo React esegue l'effetto due volte. L'hook non va cambiato perché il cleanup della prima esecuzione scarta la sua connessione e la webapp la chiude quando parte la seconda.