Rework home page to use $state, $props, and $derived

This commit is contained in:
qowevisa 2024-12-01 19:53:22 +02:00
parent 5716d1ebc4
commit 7aa2fcd504
2 changed files with 61 additions and 50 deletions

View File

@ -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: [] };
}
};

View File

@ -13,22 +13,18 @@
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) => ({
let charts: Chart[] = [];
let configs: ChartConfiguration[] = $derived(
expensesData.map((chart) => ({
type: "doughnut",
data: {
labels: chart.elements.map((type) => type.name),
@ -40,21 +36,18 @@
},
],
},
}));
}
} 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();
onMount(() => {
if (expensesData && canvases.length > 0) {
createTypeCharts();
}
});
onDestroy(() => {
@ -67,7 +60,11 @@
{/if}
<!-- Render canvas elements for charts -->
<div class="flex items-center justify-center">
<div class="container mx-auto my-8 bg-gray-100 p-6">
<h2 class="text-2xl mb-4 font-bold text-center block">
Expenses doughnut charts
</h2>
<div class="flex items-center justify-center">
<div
class="{configs.length > 4
? 'grid-cols-4'
@ -78,12 +75,13 @@
<div class="type-chart">
<canvas bind:this={canvases[index]}></canvas>
<span class="flex justify-center"
>{`Total: ${NumberToFPA(data[index].total)} ${data[index].label}`}</span
>{`Total: ${NumberToFPA(expensesData[index].total)} ${expensesData[index].label}`}</span
>
</div>
</div>
{/each}
</div>
</div>
</div>
<style lang="postcss">