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

External CSS File causing improper sizing of canvas image

I have been working on implementing the HTML5 canvas element. To draw an image into the canvas, I am using the following javascript code: var img = new Image(); var canvas = this.e; var ctx = canvas.getContext('2d'); img.src = options.imageSrc; ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...

Prevent the use of harmful language by implementing jQuery or JavaScript

Is there a way for me to filter certain words (such as "sex") using regex, even when people use variations like "b a d", "b.a.d", or "b/a/d"? How can I prevent these kinds of words from getting through? I'm trying to filter more than just one word - ...

What is the solution for getting rid of the "clear sort" state in an angular-ui-grid column header?

I am looking for information on how to remove the default behavior where the 3rd click disables sort and stays "neutral" on sortable headers. Having a disable sort state seems flawed as it does not change the sort order. How can I eliminate the 3rd state ...

Compatibility issues between jQuery and AngularJS are causing problems

Currently, I am facing a compatibility issue between RequireJS and Angular in my setup. Everything functions without any problems when using jQuery version 1.7.2. However, I wanted to upgrade to jQuery 1.8.1 along with jQuery UI, but unfortunately, my Angu ...

Can the environment variables from the .env package be utilized in npm scripts?

I've integrated dotenv into my cypress project and defined variables in a .env file, as shown here: USER=Admin How can I utilize the env variable USER within my npm scripts? "scripts": { "cypress:open": "npx cypress ope ...

Exploring the world of Javascript: The significance of variable scope and its

Encountered a unique challenge while attempting to execute an ajax call and confine the function's actions to itself. Below is the code snippet: $(document).on('click', 'input.action', function(event) { var self = this; ...

Using json_encode with chart.js will not produce the desired result

I am attempting to utilize chart.js (newest version) to generate a pie chart. I have constructed an array that I intend to use as the data input for the chart. This is the PHP code snippet: <?php if($os != null) { $tiposOs = array('Orçamento ...

Having trouble installing gulp locally due to an error with ` ode_modulesansi-regex`

While attempting to set up Gulp on my Windows 10 system, I encountered an error during the local installation process. $ node -v v9.10.1 $ npm -v 5.6.0 I successfully installed Gulp globally: $ npm install --global gulp-cli $ gulp -v CLI version 2.0.1 ...

Establishing a restricted channel exclusive to a specific role for joining

I want to create a special channel where only members from the partyInvitees collection (Collection<Snowflake, GuildMember>) can join. const permission = Discord.Permissions.FLAGS; message.guild.createRole({ name: message.author.username + "&apos ...

React - dynamically injecting external logic during execution

My goal is to modularize my React application by loading additional logic (such as containers/components) dynamically from an external .js file during runtime. For instance, I want to be able to introduce a new tab with completely different functionality o ...

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

Transfer text from one form to a text field on a different website

I've created a form that allows users to input numbers in a field and then directs the page to a specific URL. Here's the code snippet: <html> <head> <meta charset="utf-8"> <title>Tracking</title> </head& ...

Use JavaScript to generate an HTML element that has an attribute mirroring its text content

Trying to figure out how to create an HTML element similar to this: <option value="Replaced">by this</option> For example: <option value="ThisIsTest">ThisIsTest</option> UPDATE Using jQuery, I need to achieve something like thi ...

Interacting with local data using Express server

I am currently in the process of developing a web application for my web art class using Node.js with npm and Express. The concept behind the site is to have the entire body colored in one solid color, but allow users to text a hexcode/CSS color to a Twili ...

Learn the process of flipping an element when a button is clicked!

I want to use the jquery flip.js library to flip an element. However, I only want the element to flip when I click on a specific flip button, and then flip back again when another button is clicked. Any suggestions on how to achieve this functionality? ...

Difficulty with BCRYPT retrieving information from MySQL

As a beginner in programming, I've hit a roadblock and can't seem to find any solutions. I've managed to successfully register users into my database and hash their passwords. Now, I'm trying to implement a login feature for these users ...

How to handle the discrepancy between NextJS exporting files with a .html extension, yet in the <Link> component there is no .html specified

I have been working on my NextJS application and I've realized that all the links within it are built using the <Link href="/my-page"><a>My page</a></Link> component. After exporting the app to generate a static site, ...

When utilizing Reactjs, accessing an element by its id becomes challenging when the element is nested within a map() function

Currently, I am encountering an issue related to reactjs. In my scenario, I have a requirement to compare the height of the screen with a specific div to determine its maximum width. The challenge lies in the fact that the particular div I need to analyz ...

Employing jQuery Mobile with MVC3 for seamless auto-submit functionality

When I remove jQuery Mobile, the code works perfectly! The form: @using (Html.BeginForm("SearchTown", "Home", FormMethod.Post, new { id = "TheForm1" })) { @Html.DropDownList("TownID", (SelectList)ViewBag.TownId, "Select a Town") } The Javascript: & ...