Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 73905

How to access function inside a javascript fetch from html page

$
0
0

i am trying to make a website showing a graph based on some user uploaded json files. I am using a fetch to get the JSON data from a servlet and i make the graph inside the fetch, this works fine. Only i'd like to make a addData() function to add extra data to the same plot. The problem is i can't access the data outside of the fetch request and i can't acces the addData() function from my html page if it's in the fetch in my javascript file. Is there a good way to approach this problem?

my JavaScript code:


fetch('/json_storage')
    .then((response) => {
        return response.json();
    })
    .then((myJson) => {
        let hrdata = myJson[0].heartRate;
        let timestamp = hrdata.map(t => { return t.timestamp });

        let bpm = hrdata.map( b => {return b.bpm});


        let ctx = document.getElementById('canvas').getContext('2d');
        let canvas = new Chart(ctx, {
            type: 'line',
            data: {
                labels: timestamp,
                datasets: [{
                    label: new Date(timestamp[0]),
                    data: bpm,
                    backgroundColor: 'rgba(255,0,55,0.25)',
                    pointRadius: 0
                }]
            },
            options: {
                title: {
                    display: true,
                    text: 'The course of your heart rate during the day'
                },
                scales: {
                    xAxes: [{
                        type: 'time',
                        time: {
                            unit: 'hour'
                        }
                    }]
                }
            }
        });

        function addData() {
            for (let i =1; i < myJson.length; i++){
                let hrdata = myJson[i].heartRate;
                let bpm = hrdata.map( b => {return b.bpm});
                let timestamp = hrdata.map(t => { return t.timestamp });

                canvas.data.data = bpm;
                canvas.data.labels = timestamp;

                canvas.update();

            }
        }

    });


and my HTML code:

<button id="addData">Add dataset</button>
<canvas id="canvas" width="300" height="300"></canvas>

Viewing all articles
Browse latest Browse all 73905

Trending Articles



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