Creating a live data store
I’m thinking of creating a store for live data, and to start, I want to simulate data updates with setInterval, almost like using WebSocket. I’ll need to integrate actual WebSocket later. Inside Svelte components, I want to utilize D3 for scales, axes, and transitions. There’s a challenge since both D3 and Svelte manipulate the DOM. The best approach might be to let Svelte handle the data and layout while D3 takes care of scales and paths. Since the user prefers D3, I’ll suggest it be integrated as a chart component that updates based on data changes. Let's outline a proposed file structure!Building a dynamic dashboard
I’m planning to create a writable data array for stores and open a WebSocket connection. If the user prefers, I can simulate this using setInterval for a demo in +page.svelte. I aim to provide minimal, self-contained code for the page, though it might get a bit messy. Since they're looking for a "dynamic dashboard," I’ll focus on explaining how to build it rather than delivering a complete repo.
We'll start by installing Node and creating a SvelteKit project, then install D3. Finally, I’ll show how to create a live data service and discuss WebSocket integration through SvelteKit endpoints.Simplifying real-time data integration
I think it might be too much detail to dive deep into WebSockets. Instead, I can use an EventSource or SSE endpoint from SvelteKit, which is easier to manage. While many prefer WebSockets, the implementation specifics can vary based on the adapter used, like Node or Vercel. To keep things simple, I’ll focus on a front-end simulation but will mention how to connect a real-time feed. I’ll note that the user might want periodic updates through fetching or SSE listening. This way, I'm covering what they need without overcomplicating things.Structuring the SvelteKit project
I’m setting up a SvelteKit project where Svelte takes care of the UI and reactivity, while D3 focuses on drawing charts. Each chart will be a component, and I’ll use a store to hold live data. I plan to show an example of a line chart that updates every second.
For the file structure, I’ll create src/routes/+page.svelte for the layout, src/lib/LineChart.svelte for the D3 integration, and src/lib/stores.ts for writable data and the startMockStream. I should also remember to use onMount from Svelte to initialize D3, using let svg; and bind:this={svg} to get a DOM reference.Building the LineChart Component
In the LineChart.svelte file, I’m importing necessary functions from Svelte and D3 for creating a dynamic chart. I’ll set up props for data, width, and height. Using onMount, I initialize the SVG and create scales and axes in a g element. I’m wary of updating the chart before it’s fully initialized, so I’ll ensure that both svgEl and linePath are ready before updating.
I also want to make innerWidth and innerHeight reactive to changes, but for this example, I’ll keep the dimensions static for simplicity.
For the store, I’m crafting a live data store using Svelte’s writable store. I’ll set up functions to start and stop generating mock data points every second until reaching a maximum amount. Lastly, I can integrate the store with a dashboard page in +page.svelte, ensuring that the chart updates when new data arrives. I’ll also mention how to connect to a WebSocket in case the user wants real-time data. Below is a small but complete pattern you can use to build a live‑updating dashboard in SvelteKit using D3 for visualization.
It includes:
- SvelteKit project setup
- A live data store (mock stream; can be replaced with WebSockets/SSE)
- A reusable D3-based
<LineChart> component
- A dashboard page that wires everything together
1. Set up SvelteKit + D3
# Create project
npm create svelte@latest live-dashboard
cd live-dashboard
# Install dependencies
npm install
npm install d3
# Run dev server
npm run dev
2. Live data store (simulating streaming data)
Create a store that keeps a sliding window of points and updates every second.
src/lib/stores/liveData.js
import { writable } from 'svelte/store';
const MAX_POINTS = 50; // window size
function createLiveDataStore() {
const { subscribe, update, set } = writable([]);
let timer = null;
function start() {
if (timer) return; // already running
set([]); // reset
timer = setInterval(() => {
const point = {
timestamp: new Date(),
value: 50 + Math.random() * 50 // mock value
};
update((current) => {
const next = [...current, point];
if (next.length > MAX_POINTS) next.shift();
return next;
});
}, 1000);
}
function stop() {
if (!timer) return;
clearInterval(timer);
timer = null;
}
return { subscribe, start, stop };
}
export const liveSeries = createLiveDataStore();
You can later replace the setInterval section with WebSocket/SSE data, but keep the store API (subscribe, start, stop).
3. D3 Line Chart component
A Svelte component that uses D3 to render and update a line chart when data changes.
src/lib/components/LineChart.svelte
<script>
import { onMount } from 'svelte';
import * as d3 from 'd3';
export let data = [];
export let width = 800;
export let height = 300;
let svgEl;
const margin = { top: 20, right: 20, bottom: 30, left: 50 };
const innerWidth = width - margin.left - margin.right;
const innerHeight = height - margin.top - margin.bottom;
let xScale;
let yScale;
let xAxisG;
let yAxisG;
let linePath;
onMount(() => {
const svg = d3
.select(svgEl)
.attr('viewBox', `0 0 ${width} ${height}`)
.classed('line-chart', true);
const g = svg
.append('g')
.attr('transform', `translate(${margin.left},${margin.top})`);
xScale = d3.scaleTime().range([0, innerWidth]);
yScale = d3.scaleLinear().range([innerHeight, 0]);
xAxisG = g
.append('g')
.attr('transform', `translate(0,${innerHeight})`);
yAxisG = g.append('g');
linePath = g
.append('path')
.attr('fill', 'none')
.attr('stroke', 'steelblue')
.attr('stroke-width', 2);
if (data && data.length) {
updateChart(data);
}
});
// Whenever `data` changes and D3 is initialized, update the chart
$: if (svgEl && linePath && data && data.length) {
updateChart(data);
}
function updateChart(data) {
// Domains
xScale.domain(d3.extent(data, (d) => d.timestamp));
yScale.domain([0, d3.max(data, (d) => d.value) || 1]);
const line = d3
.line()
.x((d) => xScale(d.timestamp))
.y((d) => yScale(d.value));
// Path
linePath
.datum(data)
.transition()
.duration(300)
.attr('d', line);
// Axes
xAxisG
.transition()
.duration(300)
.call(d3.axisBottom(xScale).ticks(5).tickFormat(d3.timeFormat('%H:%M:%S')));
yAxisG
.transition()
.duration(300)
.call(d3.axisLeft(yScale).ticks(5));
}
</script>
<style>
.line-chart {
width: 100%;
height: auto;
}
.line-chart .domain,
.line-chart .tick line {
stroke: #ccc;
}
.line-chart text {
font-size: 11px;
fill: #444;
}
</style>
<svg bind:this={svgEl}></svg>
4. Dashboard page using the chart and store
Use the store in the root route and render the live-updating chart.
src/routes/+page.svelte
<script>
import { onMount, onDestroy } from 'svelte';
import { liveSeries } from '$lib/stores/liveData';
import LineChart from '$lib/components/LineChart.svelte';
let data = [];
let latestValue = null;
let unsubscribe;
onMount(() => {
// Subscribe to data
unsubscribe = liveSeries.subscribe((values) => {
data = values;
latestValue = values.length ? values[values.length - 1].value : null;
});
// Start streaming (mock)
liveSeries.start();
});
onDestroy(() => {
liveSeries.stop();
if (unsubscribe) unsubscribe();
});
</script>
<style>
main {
padding: 1.5rem;
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
background: #f4f5f7;
min-height: 100vh;
box-sizing: border-box;
}
h1 {
margin-bottom: 1rem;
}
.dashboard {
display: grid;
grid-template-columns: 1fr;
gap: 1.5rem;
}
@media (min-width: 900px) {
.dashboard {
grid-template-columns: 2fr 1fr;
}
}
.card {
background: white;
padding: 1rem 1.25rem;
border-radius: 0.5rem;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}
.stat-value {
font-size: 2rem;
font-weight: 600;
}
.muted {
color: #666;
font-size: 0.9rem;
}
</style>
<main>
<h1>Live Data Dashboard</h1>
<div class="dashboard">
<div class="card">
<h2>Live Time Series</h2>
<LineChart {data} width={800} height={300} />
</div>
<div class="card">
<h2>Current Status</h2>
{#if latestValue !== null}
<div class="stat-value">{latestValue.toFixed(2)}</div>
<div class="muted">Latest value in the last {data.length} points.</div>
{:else}
<div class="muted">Waiting for data…</div>
{/if}
</div>
</div>
</main>
Run npm run dev and open the app: the chart should update every second with new points sliding across.
5. Plugging in real live data (WebSocket / SSE)
Replace the mock setInterval in the store with a real source.
WebSocket example (client-side)
In +page.svelte (or a dedicated module):
onMount(() => {
const ws = new WebSocket('wss://your-server.example.com/stream');
ws.onmessage = (event) => {
const point = JSON.parse(event.data); // { timestamp, value }
// Push into the store
liveSeriesPush(point);
};
ws.onerror = console.error;
ws.onclose = () => console.log('WebSocket closed');
return () => ws.close();
});
You’d then change the store to expose a push(point) method instead of a start() that uses setInterval.
SSE (Server-Sent Events)
If your backend exposes an SSE endpoint:
const es = new EventSource('/api/stream');
es.onmessage = (event) => {
const point = JSON.parse(event.data);
liveSeriesPush(point);
};
The key idea: keep Svelte’s store as the single source of truth; D3 charts are fully declarative based on store data, so live updates become trivial.
If you want, I can extend this with:
- Additional chart types (bar/pie/area) wired to the same live store
- Multiple streams and panels on the same dashboard
- Example of an SSE or WebSocket endpoint implemented in SvelteKit (Node adapter)