0

I'm currently writing a simple note (well, 'assignment') web app using Hapi as the backend and PostgreSQL as database. My current problem is on a route for getting all notes, I'm having trouble with passing the data from database to the front-end.

Here is my code :

        method: 'GET',
        path: '/report',
        // TODO Process data from DB into preformat text & table view
        handler: (request, h) => {

            const currentWeek = new Date().getWeek()
            getReport = `
            SELECT * FROM main_assignment WHERE week = ${currentWeek-1}
            `
            let tableArray= new Array
            let finalTable = ''

            //FIXME: show finalTable on view

            client.connect()
            client.query(getReport, (err, res) => {
                res.rows.forEach(element => {
                    const temp = `
                        <tr>
                        <td>${element.id}</td>
                        <td>${element.name}</td>
                        <td>${element.assignment}</td>
                        </tr>`
                    tableArray.push(temp)
                });
                finalTable = tableArray.join('')

                console.log(finalTable)
                return h.view('report', {
                    finalTable
                })
            })

            return h.view('report', {
                finalTable
            })

When I refreshed the page, the table did not get populated. turns out the output of finalTable is blank. I tried to log it out inside the client.query() function and it actually came out the way I want (filled with datas from the forEach iterations). Now here are the things I know

  1. I still haven't got the full grasp on asynchronous concept. This is probably where I screw up, I'm ashamed to admit that I've reread the whole concept and still haven't got a clear idea on how it works and it's usage
  2. Yes, the data passing sucks (new string, convert all response to array, join all the array to the previous string). I.... don't know any better way to write it better so please change it as you like

Are there any way to fix the code so I could pass the finalTable value to the front-end side?

Thanks in advance!

Audi
  • 33
  • 3

0 Answers0