Search code examples
javascripthandlebars.jschart.jsexpress-handlebars

Getting data into script tag from route?


I have almost everything I need to get everything working just as I want it, I’m only missing one thing.

This is my get request:

app.get('/:username/tasks', function (req, res) {

    if (req.session.user === req.params.username) {
        var photo;
        countList = [],
            categoryList = [];

        db.User.findOne({
            where: {
                username: req.session.user
            }
        }).then(function (info) {
            console.log(info.dataValues.picURL);
            photo = info.dataValues.picURL
        })

        db.Tasks.findAndCountAll({
            attributes: ['category'],
            where: {
                UserUsername: req.session.user
            },
            group: 'category'
        }).then(function (result) {
            for (var i = 0; i < result.rows.length; i++) {
                categoryList.push(result.rows[i].dataValues.category);
                countList.push(result.count[i].count);
            }
            console.log(categoryList);
            console.log(countList);
        })

        db.Tasks.findAll({
            where: {
                UserUsername: req.params.username
            }
        }).then(function (data) {
            res.render('index', {
                data: data,
                helpers: {
                    photo: photo,
                    countList: countList,
                    categoryList: categoryList
                }
            })
        });
    } else {
        res.redirect('/');
    }
})

The “findAndCountAll” function gives me this in return:

[ 'Health', 'Other', 'Recreational', 'Work' ] [ 5, 1, 1, 1 ]

Which are exactly the two arrays I need. The problem is that I need to pass these values into a javascript script tag. When I send them to index.handlebars with the helper function in “Tasks.findAll” I get the values. The problem is that if I add a script tag and pass the values into that script tag, it doesn’t work. How else can I get these values into that script tag? That’s the last piece of the puzzle.

Here is the js file I'm trying to put the data into:

var ctx = document.getElementById("myChart").getContext('2d');

var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: [MISSING DATA HERE],
        datasets: [{
            label: '# of Votes',
            data: [MISSING DATA HERE],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
            ],
            borderColor: [
                'rgba(255,99,132,1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
            ],
            borderWidth: 1
        }]
    },
});

I wrote in caps where the missing data is in the file.

Any help is much obliged.


Solution

  • You should run all those queries in parallel using Promise.all and when all of them done render chart

    const userPromise =  db.User.findOne({
                           where: {
                             username: req.session.user
                           }
                         });
    
    const tasksWithCountPromise = db.Tasks.findAndCountAll({
                    attributes: ['category'],
                    where: {
                        UserUsername: req.session.user
                    },
                    group: 'category'
                }).then(function (result) {
                    for (var i = 0; i < result.rows.length; i++) {
                        categoryList.push(result.rows[i].dataValues.category);
                        countList.push(result.count[i].count);
                    }
                    return { countList, categoryList };
                });
    
    const allTasksPromise = db.Tasks.findAll({
                    where: {
                        UserUsername: req.params.username
                    }
                });
    
    Promise.all(userPromise, tasksWithCountPromise, allTasksPromise)
     .then(([user, tasksWithCount, allTasks]) => {
         res.render('index', {
                    data: allTasks,
                    helpers: {
                        photo: user.dataValues.picURL,
                        countList: tasksWithCount.countList,
                        categoryList: tasksWithCount.categoryList
                    }
                })
       });