After creating a Skeleton Project using the command npm create svelte@latest myapp
, I proceeded to install Chart.js with
npm install svelte-chartjs chart.js
and then created a basic bar chart:
<script>
import { Bar } from 'svelte-chartjs';
import { Chart, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js';
Chart.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale);
let numbers = [10, 20, 30];
let dates = ['1/1/2024', '1/2/2024', '1/3/2024'];
$: data = {
labels: dates,
datasets: [
{
label: 'Random Number',
data: numbers,
backgroundColor: 'rgba(98, 182, 239,0.4)',
borderColor: 'rgba(98, 182, 239, 1)',
borderWidth: 2
}
]
};
let options = {
responsive: true,
maintainAspectRatio: false
};
async function generate() {
const response = await fetch('/generate');
let fetchedData = await response.json();
dates = fetchedData.dates;
numbers = fetchedData.numbers;
}
</script>
<h1>Fetch Data from API endpoint</h1>
<button on:click={generate}>Request</button>
<div>
<Bar {data} {options} />
</div>
The data is fetched from the /generate
API endpoint which generates random numbers (between 10 and 30) and corresponding dates. Pressing the Request button updates the bar chart with new values. The output image can be viewed https://i.sstatic.net/G0k7u.png.
The contents of the routes/generate/+server.js
file (simulating the API endpoint) that updates the arrays are as follows:
import { json } from '@sveltejs/kit';
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
function generateDates(numDates) {
var today = new Date();
var dates = []
for (let i = 0; i < numDates; i++) {
let dateString = today.toLocaleDateString('en-US');
dates.push(dateString);
today.setDate(today.getDate() + 1);
}
return dates;
}
export function GET() {
let length = getRandomNumber(1, 10);
let numberData = Array.from({ length: length }, () => getRandomNumber(10, 30));
let dateData = generateDates(length);
return json({dates: dateData, numbers: numberData});
}
The data length is randomly chosen between 1 and 10, starting from the current date. An example response from the API endpoint looks like:
{"dates":["2/8/2024","2/9/2024","2/10/2024"],"numbers":[14,23,23]}
To enhance readability and reusability, I aim to separate the Bar
chart-specific code into a distinct component. However, I want the labels and dataset attributes to reactively update when new data is fetched.
If you have any suggestions on how to achieve this, please share!