Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

How to update a chart with data coming from an API endpoint in Svelte?

$
0
0

I am using the Svelte JS web framework with the Chart.js charting library to plot a bar chart. I have created a Skeleton project and installed the svelte-chartjs and the chart.js packages:

npm install svelte-chartjs chart.js

Under the routes folder, I made the generate/+server.js endpoint to simulate the API calls:

import { json } from '@sveltejs/kit';function getRandomNumber(min, max) {  return Math.floor(Math.random() * (max - min) + min);}export function GET() {  let randomNumbers = Array.from({ length: 12 }, () => getRandomNumber(10, 20));  return json(randomNumbers);}

It generates 12 random integer numbers between 10 and 20. Now, I can call this endpoint using the fetch('/generate') function on the root page. The content of the routes/+page.svelte file is the following:

<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 fetchedData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];  let data = {    labels: ['January','February','March','April','May','June','July','August','September','October','November','December'    ],    datasets: [      {        label: 'Random Number',        data: fetchedData,        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');    fetchedData = await response.json();  }</script><h1>Fetch Data from API endpoint</h1><button on:click={generate}>Request</button><p>Current data: {fetchedData}</p><div><Bar {data} {options} /></div>

I have initialized the data with 1 to 12 integers, which is changed when clicking the Request button. Therefore, the data fetching is successful however the bar chart is not updated with the newly generated values.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>