What is the best way to extract information from my MYSQL database and represent it as an array?

Currently, I am working on a backend API that utilizes a MySQL database. My goal is to extract data from this database and utilize it to plot latitude and longitude points on a map using the Google Maps API. To achieve this, I have integrated the Gmaps API with Nuxt JS.
Despite my efforts, I encountered an error message stating:

"Cannot read properties of undefined (reading 'coordinates')"

The code snippet below showcases my attempt to retrieve data:

async function getData(){
  const {data} = await this.$axios.$get('http://localhost:8000/api/parkingPlace');
  console.log(data)
  return {data}
}

Subsequently, I aim to pass this data into my Gmaps instance.

export default {
  data() {
    return {
      currentLocation: {},
      circleOptions: {},
      parkingPlaces: getData(),

This data will then be used to fetch and display values for latitude and longitude as pins on the map.

<template>
  <div class="min-h-screen relative max-6/6" > ;
    <GMap class="absolute inset-0 h-100% bg-blue-400"
      ref="gMap"
      language="en"
      :cluster="{options: {styles: clusterStyle}}"
      :center="{lat:parkingPlaces[0].coordinates.lat, lng: parkingPlaces[0].coordinates.lng}"
      :options="{fullscreenControl: false, styles: mapStyle}"
      :zoom="5">

      <GMapMarker
        v-for="location in parkingPlaces"
        :key="location.id"
        :position="{lat: location.coordinates.lat, lng: location.coordinates.lng}"
        :options="{icon: location.free_spots > 0 ? pins.spacefree : pins.spacenotfree}"
        @click="currentLocation = location"
      >
        <GMapInfoWindow :options="{maxWidth: 200}">
          <code>
            lat: {{ location.coordinates.lat }},
            lng: {{ location.coordinates.lng }}
          </code>
        </GMapInfoWindow>
      </GMapMarker>
      <GMapCircle :options="circleOptions"/>
    </GMap>
  </div>
</template>

The complete index.vue script where I attempt to implement this functionality can be found below.

<template>
  <div class="min-h-screen relative max-6/6" > ;
    <GMap class="absolute inset-0 h-100% bg-blue-400"
      ref="gMap"
      language="en"
      :cluster="{options: {styles: clusterStyle}}"
      :center="{lat:parkingPlaces[0].coordinates.lat, lng: parkingPlaces[0].coordinates.lng}"
      :options="{fullscreenControl: false, styles: mapStyle}"
      :zoom="5">

      <GMapMarker
        v-for="location in parkingPlaces"
        :key="location.id"
        :position="{lat: location.coordinates.lat, lng: location.coordinates.lng}"
        :options="{icon: location.free_spots > 0 ? pins.spacefree : pins.spacenotfree}"
        @click="currentLocation = location"
      >
        <GMapInfoWindow :options="{maxWidth: 200}">
          <code>
            lat: {{ location.coordinates.lat }},
            lng: {{ location.coordinates.lng }}
          </code>
        </GMapInfoWindow>
      </GMapMarker>
      <GMapCircle :options="circleOptions"/>
    </GMap>
  </div>
</template>

<script>
async function getData(){
  const {data} = await this.$axios.$get('http://localhost:8000/api/parkingPlace');
  console.log(data)
  return {data}

export default {
  data() {
    return {
      currentLocation: {},
      circleOptions: {},

      parkingPlaces: getData(),

      // Dispatched API response example:
      //   {
      //     "id": 1,
      //     "name": "Chandler Larson",
      //     "post": "37757",
      //     "coordinates": {
      //       "lng": -51.84,
      //       "lat": -60.02
      //     },
      //     "total_spots": 0,
      //     "free_spots": 0
      //   }
      // ],

      pins: {
        spacefree: "/parkingicongreen3.png",
        spacenotfree: "/parkingiconred3.png",
      },
      mapStyle: [],
      clusterStyle: [
        {
          url: "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m1.png",
          width: 56,
          height: 56,
          textColor: "#fff"
        }
      ]
    }
  }
}
</script>

I utilized Axios to retrieve data from my database and showcase them on the Google Maps interface.

I anticipate visualizing points on the map based on the latitude and longitude fetched from my database.

EDIT 1:

Modifications were implemented according to @kissu's advice.

<template v-if="parkingPlaces.length > 0">
  <div class="min-h-screen relative max-6/6" > ;
    <GMap class="absolute inset-0 h-100% bg-blue-400"
      ref="gMap"
      language="en"
      :cluster="{options: {styles: clusterStyle}}"
      :center="{lat:this.parkingPlaces[0].coordinates.lat, lng: this.parkingPlaces[0].coordinates.lng}"
      :options="{fullscreenControl: false, styles: mapStyle}"
      :zoom="5">

      <GMapMarker
        v-for="location in parkingPlaces"
        :key="location.id"
        :position="{lat: location.coordinates.lat, lng: location.coordinates.lng}"
        :options="{icon: location.free_spots > 0 ? pins.spacefree : pins.spacenotfree}"
        @click="currentLocation = location"
      >
        <GMapInfoWindow :options="{maxWidth: 200}">
          <code>
            lat: {{ location.coordinates.lat }},
            lng: {{ location.coordinates.lng }}
          </code>
        </GMapInfoWindow>
      </GMapMarker>
      <GMapCircle :options="circleOptions"/>
    </GMap>
  </div>
</template>

<script>

// async function getData(){
//   const {data} = await this.$axios.$get('http://localhost:8000/api/parkingPlace');
//   console.log(data)
//   return {data}
// }

export default {

  data() {
    return {
      currentLocation: {},
      circleOptions: {},
      parkingPlaces: [],

      pins: {
        spacefree: "/parkingicongreen3.png",
        spacenotfree: "/parkingiconred3.png",
      },
      mapStyle: [],
      clusterStyle: [
        {
          url: "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m1.png",
          width: 56,
          height: 56,
          textColor: "#fff"
        }
      ]
    }
  },

  async fetch(){
    this.parkingPlaces = await fetch('http://localhost:8000/api/parkingPlace').then(res => res.json())
    console.log(this.parkingPlaces)
  }

}

</script>


Check out the output of console.log(this.parkingPlaces)

https://i.sstatic.net/KA7EO.png

EDIT 2

https://i.sstatic.net/u1n9m.png

Answer №1

Revise

Your this.parkingPlaces object seems to be at the end based on your console.log.
To access the actual data in an iterable array format, you need to do the following:

async fetch() {
  const response = await fetch('http://localhost:8000/api/parkingPlace')
  const json = await response.json()
  this.parkingPlaces = json.data
  console.log(this.parkingPlaces)
}

Additionally, I suggest utilizing the this.$axios.$get shortcuts as shown here.


Can you clarify what getData is? Consider moving that function into a methods within your export default { block.
You can then use either asyncData() or the fetch() hook to properly fetch the data in a Nuxt manner, and call this.getData within them.

Add a conditional statement in your template for fallback (specifically for the fetch() lifecycle hook). asyncData does block rendering.
A simple

v-if="parkingPlaces.length"
should suffice, no need for more complexity.
However, avoid stacking both as ESLint might flag it.

Refer to this example, using $fetchState.pending to ensure data availability before iteration over the array. Otherwise, you may encounter errors with empty data sets.

The template section may not anticipate async data retrieval. Hence, incorporating a conditional helps it handle potentially empty results from async fetching.


For more insights on data fetching in Nuxt, check out: https://nuxtjs.org/docs/features/data-fetching#the-fetch-hook

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

Troubleshooting: Issue with Dependency Injection functionality in Angular 2 starter project

I’ve encountered a strange error whenever I attempt to inject any dependency TypeError: Cannot set property 'stack' of undefined at NoProviderError.set [as stack] (errors.js:64) at assignAll (zone.js:704) at NoProviderError.ZoneAwareError (zon ...

The process of dynamically inserting input types into a <td> element using the innerHTML tag is not functioning properly in Internet Explorer

I am facing an issue with dynamically placing input types within a <td> tag - the innerHTML() method is not functioning properly in Internet Explorer, although it works fine in Mozilla. This is how I am inserting the input types using JavaScript, wi ...

Loading a div using Ajax within a frame

My php page includes a div that is supposed to be populated by an Ajax call. function showcopay() { var apa = document.getElementById("alert_id").value; $("#copay").load('show_copay.php?pid='+apa); } The parent page of the div used to be ...

What happens when dynamically loaded static resources are loaded?

Currently, I am dynamically injecting HTML into a page using JQuery AJAX. The injected HTML contains script and link tags for JS and CSS files respectively. The issue I am facing is that my initPage() function runs before the script containing its definiti ...

Decoding JSON using JavaScript

I am dealing with a webservice that uses RestEasy to return a JSON object with a List element. When I try to parse the results in a JavaScript loop, everything works fine if there are two or more elements in the List. However, if there is only one element, ...

When you click on the "email" link, the Email app will automatically launch

Is there a way I can make the "EMAIL" text clickable in HTML, so that it automatically opens an email app or site and inserts the clicked email into the "To:" field? ...

Need jQuery solution for changing CSS in numerous locations upon hover

Currently, I am working on a WordPress website and I am trying to figure out how to change the CSS color of a side navigation element when a remote image is hovered over. In a typical scenario, I would accomplish this using CSS by assigning a hover class ...

Unleashing the power of jQuery, utilizing .getJSON and escaping

When I use .getJSON, the response I get is a JSON string with many \" characters. However, the callback function does not fire when the page is launched in Chrome. I have read that this happens because the JSON string is not validated as JSON (even th ...

Text area featuring unique border design, with border color change upon focus?

Currently, I have a text area with borders that are designed in a unique way. However, I am looking to change the border color when the user focuses on the text area. Do you have any suggestions on how I can achieve this effect without affecting the curre ...

Navigating through and extracting data from an object in JavaScript

Given the function call destroyer([1, 2, 3, 1, 2, 3], 2, 3);, I am trying to retrieve the last 2, 3 part after the initial array. However, I am unsure about how to achieve this. When I use return arr[6]; or return arr[1][0], both statements do not return ...

A guide on identifying the data type of a value entered into an HTML table using JavaScript

Currently, I am tackling a contenteditable HTML table challenge. My goal is to enforce the insertion of only numeric values while alerting the user if they attempt to input strings or non-numeric characters. Can anyone provide guidance on how to achieve th ...

Utilize Axios in Vue.js to fetch and process data from a REST API endpoint in C#

After successfully creating and deploying an API on Azure, I am trying to display the response in an alert box using javascript (Vue.js). The test method of my API returns the string "working". You can test the API here. This is the code snippet from my A ...

Developing a JavaScript library that utilizes flow type annotations and provides access to various data types

I am currently developing a library intended for use by third parties. I have opted to utilize flowtype as the typing system for specific reasons within my organization. This library presents React components with annotations. The library itself is annota ...

When exporting data from Datatable to Excel, decimal values including the % symbol may experience rounding issues

I am facing an issue when trying to export a Datatable to an excel sheet. The column in the Datatable contains decimal values with a % symbol. However, after exporting, the decimal values are being rounded off. I need the decimal values along with the % sy ...

Identify the externally-sourced element of interest

I'm attempting to apply a ScrollReveal effect to an element loaded from a separate html file called "header.html". Unfortunately, the ScrollReveal animation is not working on this particular element, while other elements within my index.html are funct ...

How to hide an item in Ionic 2 using navparams

Is there a way to dynamically hide or show a list item on page load depending on certain parameters? Here is an example of the code I am currently using: HTML <button ion-item (tap)="goToPage2()" [hidden]="shouldHide">Page 2</button> TS ex ...

Displaying Dynamic Content in React Table Rows Based on Conditions

I'm populating a table with multiple rows using props. If a returned prop is an empty string "" , I want to exclude that row from rendering. <Table.Body> <Table.Row> <Table.Cell>Producer</Table.Cell> ...

Mastering Node.js: Writing to a Write Stream on the 'finish' Event

I'm currently using Node.js streams to process a text file line by line, apply some transformations, and then generate an SVG file based on the data. However, I am facing an issue where when I try to write the closing tag (</svg>) after all pro ...

JavaScript's efficient way to target multiple class names

My goal is to extract and process JSON data into specific instances of a class named "slide_content" I want to achieve something like this: slide_content[0] Unfortunately, JS does not offer a method like getElementByClass(). The relevant API data can b ...

What is the best way to apply dynamic wrapping of a substring with a component in Vue.js?

My Objective My goal is to take a user input string and render it with specific substrings wrapped in a component. Specifically, I am looking to identify dates within the string using a regex pattern and then wrap these dates in a Vuetify chip. Progress ...