aboutsummaryrefslogtreecommitdiff
path: root/fe/src/lib/DataView.svelte
blob: 7f368c67dcb7d37bde5ae813f4df9a5ce3b99f3e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<script lang="ts">
    import { onDestroy, onMount } from "svelte";
    import { token } from "../stores/auth";
    import Table from "./Table.svelte";
    import Chart from "chart.js/auto";
    import AddForm from "./forms/AddForm.svelte";

    let open: boolean = false;

    let json: Promise<any>;

    let canvasRef: HTMLCanvasElement;
    let chart: any;

    async function fetchData() {
        const res = await fetch("http://localhost:8080/api/v1/stats/", {
            method: "GET",
            headers: {
                Authorization: `Bearer ${$token}`
            }
        });
        if (res.ok) {
            json = res.json();
        } else {
            throw new Error("There was a problem with your request");
        }
    }

    function handleClick() {
        open = true;
    }

    function closeDialog() {
        open = false;
    }

    function onStatisticAdd() {
        open = false;
        fetchData();
    }

    onMount(() => {
        fetchData();
        chart = new Chart(canvasRef, {
            type: "bar",
            data: {
                labels: ["one", "two"],
                datasets: [
                    {
                        label: "Water",
                        data: [1, 2],
                        backgroundColor: "rgba(75, 192, 192, 0.2)",
                        borderColor: "rgba(75, 192, 192, 1)",
                        borderWidth: 1
                    }
                ]
            }
        });
    });

    onDestroy(() => {
        if (chart) chart.destroy();
        chart = null;
    });
</script>

<div>
    <button on:click={handleClick}>Add</button>
    <canvas bind:this={canvasRef} />
    <AddForm {open} on:submit={onStatisticAdd} on:close={closeDialog} />
    {#await json then data}
        <Table {data} nofooter />
    {:catch error}
        <p>{error}</p>
    {/await}
    <!-- <Chart /> -->
</div>

<style>
    dialog {
        background: red;
        box-shadow: 0 20px 5em 10px rgba(0, 0, 0, 0.8);
    }

    dialog::backdrop {
        padding: 20px;
        box-shadow: 20px 20px rgba(0, 0, 0, 0.8);
        background-color: red;
    }
</style>