Skip to content

A chart of a number over time ​

A chart of a number over time needs the earlier values as well as the newest one. data, however, holds only the newest value of each name. dataHistory(name) returns the recent values of one name from the oldest to the newest with the time of each. In the example the greenhouse sends a new temperature twice a second and the view draws the history as a line that it redraws at every new value.

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

// In the fake greenhouse, the temperature changes twice a second.
const greenhouse = {
	name: 'Greenhouse',
	data: { temperature: { every: 500, value: (time) => Math.round((22 + 2 * Math.sin(time / 3000)) * 10) / 10 } },
};

// The range of the chart, in °C, and its size.
const LOW = 18;
const HIGH = 26;
const WIDTH = 300;
const HEIGHT = 100;

// Turns the readings into the points of an SVG line, the oldest on the left and the newest on the right.
function pointsOf(history) {
	const step = WIDTH / Math.max(history.length - 1, 1);
	return history.map((reading, index) => `${index * step},${HEIGHT - ((reading.value - LOW) / (HIGH - LOW)) * HEIGHT}`).join(' ');
}

// A line of the recent temperatures.
function TemperatureChart({ world }) {
	const [history, setHistory] = useState([]);

	useEffect(() => {
		// dataHistory() gives the recent values of one name, oldest first (await it).
		const load = async () => setHistory(await world.dataHistory('temperature'));
		load();
		// Load them again at every new reading.
		return world.onData('temperature', load);
		// This runs once, because `dataHistory` and `onData` work from any copy of `world`.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return (
		<>
			<svg viewBox={`0 0 ${WIDTH} ${HEIGHT}`} width={WIDTH} height={HEIGHT} style={{ border: '1px solid #8888' }}>
				<polyline points={pointsOf(history)} fill="none" stroke="#d35400" strokeWidth="2" />
			</svg>
			<p>The last {history.length} readings, from {LOW} to {HIGH} °C.</p>
		</>
	);
}

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<h2>{world.name}</h2>
			<p>Temperature now: {world.data.temperature} °C</p>
			<TemperatureChart world={world} />
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// In the fake greenhouse, the temperature changes twice a second.
const greenhouse = {
	name: 'Greenhouse',
	data: { temperature: { every: 500, value: (time) => Math.round((22 + 2 * Math.sin(time / 3000)) * 10) / 10 } },
};

// The range of the chart, in °C, and its size.
const LOW = 18;
const HIGH = 26;
const WIDTH = 300;
const HEIGHT = 100;

// Turns the readings into the points of an SVG line, the oldest on the left and the newest on the right.
function pointsOf(history) {
	const step = WIDTH / Math.max(history.length - 1, 1);
	return history.map((reading, index) => `${index * step},${HEIGHT - ((reading.value - LOW) / (HIGH - LOW)) * HEIGHT}`).join(' ');
}

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

const title = document.createElement('h2');
const reading = document.createElement('p');
const SVG = 'http://www.w3.org/2000/svg';
const chart = document.createElementNS(SVG, 'svg');
chart.setAttribute('viewBox', `0 0 ${WIDTH} ${HEIGHT}`);
chart.setAttribute('width', WIDTH);
chart.setAttribute('height', HEIGHT);
chart.style.border = '1px solid #8888';
const line = document.createElementNS(SVG, 'polyline');
line.setAttribute('fill', 'none');
line.setAttribute('stroke', '#d35400');
line.setAttribute('stroke-width', '2');
chart.append(line);
const caption = document.createElement('p');
document.body.append(title, reading, chart, caption);

world.subscribe((node) => {
	title.textContent = node.name;
	reading.textContent = `Temperature now: ${node.data.temperature} °C`;
});

async function drawChart() {
	// dataHistory() gives the recent values of one name, oldest first (await it).
	const history = await world.dataHistory('temperature');
	line.setAttribute('points', pointsOf(history));
	caption.textContent = `The last ${history.length} readings, from ${LOW} to ${HIGH} °C.`;
}

drawChart();
// Draw it again at every new reading.
world.onData('temperature', drawChart);
Live, on a fake world
Open

How it works ​

  1. The webapp keeps up to the last 200 values of each name for you. await world.dataHistory('temperature') returns them as [{ value, time }, …] from the oldest to the newest. Always await the call because in the webapp it returns a Promise.
  2. world.onData('temperature', load) calls load at every new value and load draws the chart again from the history.
  3. The chart is one SVG <polyline>. pointsOf places the values from the oldest at the left edge to the newest at the right edge and from LOW at the bottom to HIGH at the top.

See also ​

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