diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts new file mode 100644 index 0000000..29e8b74 --- /dev/null +++ b/src/routes/+page.server.ts @@ -0,0 +1,13 @@ +import type { StatsTypeCurrencyChart } from "$lib/entities"; +import type { PageServerLoad } from "./$types"; + +export const load: PageServerLoad = async ({ fetch }) => { + try { + const expensesData: StatsTypeCurrencyChart[] = await fetch("/api/statistics/type").then((res) => res.json()); + return { expensesData: expensesData }; + } catch (error) { + console.log("error in +page.server.ts", error) + return { expensesData: [] }; + } +}; + diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index ea20968..dd4ef61 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -13,48 +13,41 @@ Chart.register(DoughnutController, ArcElement, Tooltip, Legend); - let error: string | null = null; - let data: StatsTypeCurrencyChart[] = []; - let configs: ChartConfiguration[] = []; - let charts: Chart[] = []; + let { data } = $props(); + $inspect(data); + let error: string | null = $state(null); + let { expensesData }: { expensesData: StatsTypeCurrencyChart[] } = + $state(data); + $inspect("expensesData =", expensesData); + + // let expensesData: StatsTypeCurrencyChart[] = $state(data.expensesData); let canvases: HTMLCanvasElement[] = []; - - async function fetchChartStats() { - try { - const result = await fetch("/api/statistics/type"); - if (!result.ok) { - const obj = await result.json(); - error = obj.message; - } else { - data = await result.json(); - - configs = data.map((chart) => ({ - type: "doughnut", - data: { - labels: chart.elements.map((type) => type.name), - datasets: [ - { - label: chart.label, - data: chart.elements.map((type) => type.value / 100), - backgroundColor: chart.elements.map((type) => type.color), - }, - ], + let charts: Chart[] = []; + let configs: ChartConfiguration[] = $derived( + expensesData.map((chart) => ({ + type: "doughnut", + data: { + labels: chart.elements.map((type) => type.name), + datasets: [ + { + label: chart.label, + data: chart.elements.map((type) => type.value / 100), + backgroundColor: chart.elements.map((type) => type.color), }, - })); - } - } catch (e) { - console.error("Error fetching data:", e); - error = "Failed to fetch chart data."; - } - } + ], + }, + })), + ); function createTypeCharts() { charts.forEach((chart) => chart.destroy()); charts = configs.map((config, index) => new Chart(canvases[index], config)); } - onMount(async () => { - await fetchChartStats(); - createTypeCharts(); + + onMount(() => { + if (expensesData && canvases.length > 0) { + createTypeCharts(); + } }); onDestroy(() => { @@ -67,22 +60,27 @@ {/if} -