What could be causing my default prop to not be transmitted to the child component in vuejs2?

Having trouble passing a default value to my Leaflet map child component before fetching the desired data from an API endpoint. I tried using country coordinates like latitude and longitude, but it's not working as expected.

This is how I attempted to pass the values:

<template>
  <div class="home">
    <LeafletMap
      :latitude="countryStats.countryInfo.lat || 0"
      :longitude="countryStats.countryInfo.long || 0"
    />
  </div>
</template>

In another attempt:

<template>
  <div class="home">
    <LeafletMap
      :latitude="countryStats.countryInfo.lat ? countryStats.countryInfo.lat : 0"
      :longitude="countryStats.countryInfo.long ? countryStats.countryInfo.long : 0"
    />
  </div>
</template>

However, neither of these methods seem to be working for me.

When trying this out, I encounter the following error:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'lat' of undefined"

found in

---> at src/components/home/Home.vue

The displayed error refers to my child component, which looks like this:

<template>
  <div class="map">
    <h1>World Map</h1>
    <div id="mapContainer">
      <l-map
        style="height: 80%; width: 100%"
        :zoom="zoom"
        :center="center"
        @update:zoom="zoomUpdated"
        @update:center="centerUpdated"
        @update:bounds="boundsUpdated"
      >
        <l-tile-layer :url="url"></l-tile-layer>
      </l-map>
    </div>
  </div>
</template>

<script>
import "leaflet/dist/leaflet.css";
import { LMap, LTileLayer } from "vue2-leaflet";

export default {
  name: "LeafletMap",
  components: {
    LMap,
    LTileLayer
  },
  props: {
    latitude: {
      type: Number,
      default: 0
    },
    longitude: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
      zoom: 4,
      center: [this.latitude, this.longitude],
      bounds: null
    };
  },
  methods: {
    zoomUpdated(zoom) {
      this.zoom = zoom;
    },
    centerUpdated(center) {
      this.center = center;
    },
    boundsUpdated(bounds) {
      this.bounds = bounds;
    }
  }
};
</script>

<style src="./LeafletMap.css" scoped />

I am now wondering if providing default values for the props latitude and longitude in my child component is necessary or will it lead to conflicts?

If you have any suggestions or solutions, I would greatly appreciate them.

Answer №1

According to ViniciusSilveiraAlves, the issue lies within your parent component (Home), not your child component (LeafletMap).

It seems that the problem stems from the countryStats data item being initially assigned an empty object {}. This results in the template trying to access countryStats.countryInfo.lat, but since countryInfo is undefined, attempting to access its lat member triggers the error message (which the ternary operator cannot prevent at that point).

An easy solution, if appropriate for your situation, is to initialize countryStats with a more comprehensive value:

export default {
  name: "Home",
  data() {
    return {
      countryStats: {
        countryInfo: {} // Providing enough structure for the template
      }
    };
  }
}

If an empty initial countryStats object is required for some reason, you can update your template conditions to ensure that countryStats.countryInfo is defined first:

<LeafletMap
  :latitude="countryStats.countryInfo && countryStats.countryInfo.lat || 0"
  :longitude="countryStats.countryInfo && countryStats.countryInfo.long || 0"
/>

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

How to extract cookie value in a node.js application using socket.io

How can I retrieve cookie values in a node server using socket.io? Whenever a socket sends a message to the server, I need to check the value of the cookie. However, I only want to obtain the cookie value and not the session cookie as done in Express. r ...

Is there a way to prevent a web page from automatically refreshing using JavaScript?

I would like my webpage to automatically refresh at regular intervals. However, if a user remains inactive for more than 5 minutes, I want the refreshing to stop. There is an example of this on http://codepen.io/tetonhiker/pen/gLeRmw. Currently, the page ...

The Ajax call failed to connect with the matching JSON file

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script <script> function launch_program(){ var xml=new XMLHttpRequest(); var url="student.json"; xml.open("GET", url, true); xml.send(); xml.onreadystatechange=fun ...

Implement CSRF protection for wicket ajax requests by adding the necessary header

I'm currently working on a website created with Apache Wicket and we're looking to enhance its security by implementing CSRF protection. Our goal is to keep it stateless by using a double submit pattern. For forms, we are planning to include a h ...

Attempting to transmit a ng-repeat object to a personalized filter function

Objective: The goal is to enable a user to input the name of a course into the search field and view a list of students who are enrolled in that course. Data Models: course (contains course name and code) student (holds a list of courses they are regist ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

Obtain the date in ISO format without subtracting the timezone offset

I need to obtain a Date string without the timezone being added or subtracted. Currently, when I set my OS timezone to GMT +13 and create a new Date() object, the toISOString() method subtracts one day. For example, today is 11/02. If I adjust my OS time ...

Preventing a user from accessing the login page if they are already logged in using Reactjs

I need assistance with implementing a "Login Logout" module in Reactjs using the nextjs framework. My goal is to redirect users to the "dashboard" page if they are logged in (email set in cookie). However, I am encountering an error with the following co ...

The dirtyFields feature in React Hook Form is not accurately capturing all the fields that are dirty or incomplete,

I am facing an issue with one field in my form, endTimeMins, as it is not registering in the formState. I have a total of four fields, and all of them are properly recognized as dirty except for the endTimeMins field. It is worth mentioning that I am utili ...

How can PHP Ajax be used to determine when a modal should pop up?

Is there a way to automatically display a modal without refreshing the page? Currently, I have a button that submits to home.php and triggers the modal, but it requires a page refresh for the modal to appear. I'm looking for a solution that will eith ...

Is it necessary to use JS/JQ to trigger PHP form data?

Can PHP files/functions be executed without reloading the page? It can be quite disruptive when developing a chat app and every time you send a message, the entire page refreshes. I attempted to use AJAX but it didn't work. Is it not possible to send ...

Can JSON be parsed using JavaScript?

Is it feasible to utilize JavaScript to parse information from an external URL hosting a JSON file on a different domain? The JSON data sample below shows various URLs with associated "q" values that I am interested in extracting. [{"url":"http://websit ...

Utilize the jQuery autocomplete UI Widget to trigger a select event on a dynamically generated row in a table

Currently, I have successfully implemented a jQuery autocomplete feature on the text input of a table data element called txtRow1. The data for this autocomplete is fetched remotely from a MySQL database and returned in JSON format as 'value' for ...

I'm struggling to make this script replace the values within the table

I am struggling with a script that I want to use for replacing values in a google doc template with data from a google sheet. The script is able to recognize the variables and generate unique file names based on the information from the google sheet. Howev ...

Ensuring the correctness of a date input with v-validate in Vue.js

I need to set a condition where only dates that are equal to or greater than the departure date time field are allowed: <tr v-for="(input,k) in inputs" :key="k"> <datetime name="departureDateTime" v-validat ...

What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren. Here is an example: <div class="parent" > <div class="child1" > <!-- should be focused--> <div class="g ...

Elevate with Ease: Tailwind's Height Transition

I've been attempting to implement a transition effect using TailwindCSS, but I haven't found an updated version with the latest features. Here's the code snippet: <div id="fadeInElement" className={visible ? " w-2/3 px-5 t ...

Adjust the navigation menu to display or hide as the page is being scrolled

Implementing an offset to display/hide the navigation menu when the page is scrolled 100px. Attempted to modify from lastScroll = 0 to lastScroll = 100 but it did not work as expected. Jquery: Fiddle // Script lastScroll = 0; $(window).on('scroll&ap ...

Encountering an issue with receiving "undefined" values while utilizing WordPress post metadata in AngularJS

Utilizing the Wordpress REST API v2 to fetch data from my functional Wordpress website to an AngularJS application. Everything is functioning properly, however when I attempt to access post meta such as "_ait-item_item-data", it returns an error stating "u ...

"An error occurred: Uncaught SyntaxError - The import statement can only be used within a module. Including a TypeScript file into a

I need to integrate an Angular 10 TypeScript service into a jQuery file, but I am facing an issue. When I try to import the TypeScript service file into my jQuery file, I encounter the following error: Uncaught SyntaxError: Cannot use import statement outs ...