What is the best way to transfer data from a database query to Vue?

I am currently working on an API request that involves calling a SQL query within the function. I want to pass the results to a .vue page utilizing express-vue. Below is the code snippet for the API request:

router.get('/search', (req, res, next) => {

    var keyword = ("%" + req.query.keyword + "%")
    var lat = req.query.lat
    var lng = req.query.lng

    console.log(keyword, lat, lng)

    connection.query('SELECT *, ( 3959 * acos (cos ( radians(?) )* cos( radians( lat ) )* cos( radians( lng ) - radians(?) )+ sin ( radians(?) )* sin( radians( lat ) ))) AS distance FROM job_posting where job_title like ? HAVING distance < 25', [
        lat, lng, lat, keyword
    ], function(err, rows) {

     })
  res.render('main', {
  // data: {
  //           results
  //         },
    vue: {
        meta: {
            title: 'Page Title',
        },
        components: ['myheader', 'myfooter', 'searchform', , 'results']
    }

});
})

Now, let's take a look at the Main.vue page:

<template>
<div id="wrap">
    <div class="col-md-1"></div>
    <div id="main-container" class="container col-md-10">

        <myheader></myheader>
        <div class="col-md-4"></div>
        <div class="col-md-4">
        <searchform></searchform>
        <results></results>


        </div>
        <div class="col-md-4 text-center">

        </div>
        <div class="col-md-1"></div>


    </div>
</div>
</template>

I am aiming to pass the retrieved "rows" data to the results.vue component. Here is how the data looks coming from the database:

[ RowDataPacket {
    id: 1,
    job_title: 'Software Engineer',
    job_desc: '<p>Ayo</p>',
    location: 'Akron, OH',
    job_type: 'Full-Time',
    salary: '',
    date_created: 2016-11-23T05:00:00.000Z,
    short_desc: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e07071107113e19131f1712501d1113">[email protected]</a>',
    apply_url: 'Ayo',
    lat: '41.084821',
    lng: '-81.515607',
    distance: 0 },
  RowDataPacket {
    id: 2,
    job_title: 'Software Engineer',
    job_desc: '<p>Ayo</p>',
    location: 'Akron, OH',
    job_type: 'Full-Time',
    salary: '',
    date_created: 2016-11-23T05:00:00.000Z,
    short_desc: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6afafb9afb996b1bbb7bfbaf8b5b9bb">[email protected]</a>',
    apply_url: 'Ayo',
    lat: '41.084821',
    lng: '-81.515607',
    distance: 0 },
  RowDataPacket {
    id: 3,
    job_title: 'Software Engineer',
    job_desc: '<p>Ayo</p>',
    location: 'Akron, OH',
    job_type: 'Full-Time',
    salary: '',
    date_created: 2016-11-23T05:00:00.000Z,
    short_desc: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6dfdfc9dfc9e6c1cbc7cfca88c5c9cb">[email protected]</a>',
    apply_url: 'Ayo',
    lat: '41.084821',
    lng: '-81.515607',
    distance: 0 } ]

Answer №1

When it comes to express-vue, I am not familiar with it. However, I believe that making API calls directly from a route definition is not the best practice.

Instead, you should pass the lat and lng parameters to your results component and handle the API call there. This can be done using a method or utilizing the created() hook for better flexibility in changing the API implementation in the future:

res.render('main', {
  data: {
    lat,
    lng,
  },
  vue: {
    meta: {
      title: 'Page Title',
    },
    components: ['myheader', 'myfooter', 'searchform', , '
}

UPDATE

If querying data from the route is necessary and assuming that rows is an array of JavaScript objects, you can render your component within the query callback:

connection.query('SELECT *, ( 3959 * acos (cos ( radians(?) )* cos( radians( lat ) )* cos( radians( lng ) - radians(?) )+ sin ( radians(?) )* sin( radians( lat ) ))) AS distance FROM job_posting where job_title like ? HAVING distance < 25', [
    lat, lng, lat, keyword
], function(err, rows) {
  res.render('main', {
    data: {
      results: rows
    },
    vue: {
      meta: {
        title: 'Page Title',
    },
    components: ['myheader', 'myfooter', 'searchform', 'results']
  }
  next(); // Ensure to include this
})

Remember to include the next() function call.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Parameter number is invalid in PDO query

I have implemented the following PDO SQL Query: $stmt = $pdo_conn->prepare("INSERT into ticket_updates (ticket_seq, notes, datetime, updatedby, customer, internal_message) values (:ticket_seq, :notes, :datetime, :updatedby, :customer, :internal_message ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Modifying and replacing content in a local file using JavaScript

I have a file located in a directory called testfolder on my local disk. The contents of the file are as follows: Apples are red. <colour = red/> latitude 13.124165 Would it be possible to retrieve the content of this file, store it in a variable, ...

Choose the radio button by clicking using jQuery

I am attempting to use jQuery to select a radio button on click. Despite multiple attempts, I have been unsuccessful so far. Here is my current code: JS $(document).ready(function() { $("#payment").click(function(event) { event.preventDefault() ...

Using jQuery to revert back to the original SRC after mouse is not hovering over an element

I've been working on a script to change the src attribute for an icon. The icon I'm loading is a different color and it's meant to notify the user about the link associated with it. Currently, I have the src changing to the second icon on h ...

Preventing Repeated Clicks in AngularJS

Looking for a better approach to handle double clicks in AngularJS other than using ng-disabled. I have a solution to disable double/multi-click functionality on button click and re-enable it after completing an ajax process. Any suggestions? When our cod ...

Angucomplete-alt fails to display dropdown menu

On my website, there is a textarea where users need to input the name of a group project. The goal is to implement autocomplete functionality, so as users type in the project name, a dropdown menu will appear with suggestions of existing projects to assist ...

Showing undefined or null values in React and JavaScript

My goal is to format undefined or null values by italicizing them. If the value is an empty string, it should be displayed as is. If it has a value, that value should also be displayed as is. However, I am encountering an issue where null or undefined val ...

Struggling to implement CSS for second div onto selected item in the first div

As a beginner in Angular, I am seeking some guidance and examples. In my code, there are two divs. One is created using ng-repeat with an ng-click function to detect the clicked item. The other div below has CSS properties like style="width:100px; float ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

Utilizing JSON Parsing with Swift 3

Currently, I am working with an API endpoint that provides JSON data in the given format: [ { "id": "1", "name": "John" }, { "id": "2", "name": "Jane" }, { "id": "3", "name": "Nick" } ] I have been trying to parse this ...

The multiple-choice selection tool is not displaying any choices

I am having an issue with my ng-repeat code in conjunction with the jquery multiple-select plugin. Despite using this plugin for a multiple select functionality, the options generated by ng-repeat are not visible. Below is the code snippet in question: & ...

How come it functions with $scope but fails with `this`?

I am trying to figure out why my code only works with scripts 1 and 3, but not with script 2. I need this functionality for my project because I can't use $scope. Thank you!! <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.19 ...

The particular division is failing to display in its designated location

This is quite an interesting predicament I am facing! Currently, I am in the process of coding a website and incorporating the three.js flocking birds animation on a specific div labeled 'canvas-div'. My intention is to have this animation displa ...

Access model information from a controller with the help of Next.js and Sequelize

I'm currently working on a project involving Vue.js as my frontend and Next.js as my backend. While everything seems to be running smoothly, I am facing an issue with retrieving my model data back to my controller... Additional details: I have utili ...

Tips for resolving issues with async-await functions when utilizing Axios

I am trying to implement axios using the async await function in my code. However, I encountered an error when attempting to use async await. useEffect(async() => { await axios .get("https://cryptic-inlet-27003.herokuapp.com/products?size=6" ...

What is the best way to delete JSON elements from a response after Sequelize successfully creates a database record?

Can anyone help me figure out how to alter the JSON response when creating a new product in my database with Sequelize? I want to remove the updatedAt and createdAt elements. This is my current code snippet: router.post('/products', (req, res, ...

`Can you teach me how to dynamically load HTML elements using input JSON data?`

What is the best way to iterate through an input array of objects? I currently have data for only 2 people included. However, there are more than 50 people's information in the input and I need to loop through all of them. Here is a sample code snip ...

The metro bundler is facing an unexpected glitch and is stuck in the terminal, failing to load

Recently, I've been using explo-cli to work on a react native project. Everything was running smoothly until today when I encountered an error stating that it couldn't find module './iter-step'. Before this, there was also an issue with ...

Activate the places_changed event in Google Maps by clicking the submit button

I would like to activate my placed_changed function when a submit button is clicked. Here's what I have so far: I've set up a searchbox using google.maps.places.SearchBox, and when I press enter while the search box is in focus, it triggers the e ...