Issue with Vue.js displaying an undefined error for object value during loading and rendering

Hey there! I have some experience with Vue, but this particular issue is really getting to me. What am I missing here?

So, I have an object that I load via an ajax call within the mounted method:

job: {
  "title": "value",  
  "location": {
    "name":"HONG KONG"
  }
}

When I try to access {{ job.title }}, everything works fine. But when I try to access {{ job.location.name }}, I get an undefined error even though the value still shows up. And when I just try to view {{ job.location }}, I see the json object so it is defined.

It's frustrating because I know it should be simple, but for some reason, I can't figure out why it's not working as expected.

// Adding on

Here's my entire Vue class:

    const router = new VueRouter({
        mode: 'history',
        routes: []
    });
    const app = new Vue( {
      router,
      el: '#app',
      data: {
        job: {}
      },
      mounted: function () {
        var vm = this
        jQuery.ajax({
            url: 'https://xxx' + this.jobId,
            method: 'GET',
            success: function (data) {
                vm.job = data;
            },
            error: function (error) {
                console.log(error);
            }
        });
      },
      computed: {
        jobId: function() {
            return this.$route.query.gh_jid
        }
      }
    })

Answer №1

When your component is rendered, it attempts to retrieve a value from job.location.name, but the location object is undefined prior to the completion of the ajax request. This results in an error resembling

Cannot read property 'name' of undefined
.

To resolve this issue, you can create a computed property called locationName and have it return an empty string if the job object has not been loaded yet:

computed:{
//...
    locationName() {
       return this.job.location ? this.job.location.name : '';
    }
}

Alternatively, you could define a computed property for location and return an empty object if no location exists. Another solution would be to include an empty location object in your initial data (if you are certain that the API response always includes location), such as job: { location: {}}. Any of these approaches will resolve the issue.

Another option is to use the v-if directive in your template to handle this situation:

<div v-if="job.location">
   {{ job.location.name }}
   <!-- other location related content -->
</div>

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

Retrieve weight measurements from a serial port by using Node JS

I'm a novice in node.js and I'm trying to retrieve weight data from a serial port. I have nodejs(v14.19.0) and npm(6.14.16) installed, and I'm attempting to obtain weight data using localhost:8080/get_weight. However, the script isn't f ...

Click the button to increase the counter up to 2, and then decrease it back to 0 starting from 2

I'm struggling to implement this efficiently. My count keeps incrementing and decrementing by 1, causing me to get stuck at the value of 1 without going back down to zero. using react: jsfiddle The counter increases from 0 to 2 when onClick() is tri ...

Updating Child Components with a React Component

Within my React application, I have a component named Albums (defined in the code as Albums). The render() method of this component returns one of two possible components based on its internal state. When one of these components (AlbumsTable) is invoked, i ...

Dynamically insert innerHTML content into table rows using JavaScript in PHP is a fantastic way to customize

Having trouble with innerHTML in this scenario, looking to achieve something along these lines: <table width="100%" border="0" id="table2"> <?php include("connection.php"); $sql=mysql_query("select* from b1"); while($res=mys ...

Does the 'a' HTML tag secretly trigger window.location.assign?

Being relatively new to the online world, I have a simple question in mind. Imagine that I have a very basic a tag in my HTML: <a href="www.google.com"> Click me </a> What actually happens when I click on this link? Does the browser simply ...

Tips for updating a React component that fetches data from an API

I'm a beginner in React and JavaScript, working on creating a simple React webpage that fetches data from an API and displays it. My goal is to have the component automatically refresh every 60 seconds, while also giving the user the option to manuall ...

Testing React components with Jest by mocking unnecessary components

Consider a scenario where we have the Page component defined as: const Page = () => <> <Topbar /> <Drawer /> <Content /> </> When writing an integration test to check interactions within the Drawer and Con ...

Implementing momentLocalizer with moment.js in react-big-calendar alongside fullcalendar.js

I'm currently working with react-big-calendar and I require assistance in setting up localization as per the example provided on GitHub. import BigCalendar from 'react-big-calendar'; import moment from 'moment'; BigCalendar.setLo ...

The mesmerizing world of parallax animations and the smooth scrolling experience

I recently built a website using the SUPERSCROLLORAMA plugin, only to discover later that there are issues with parallax scrolling on iPad and iPhone. Now I'm trying to figure out how to solve this problem. It seems that events are disabled on these ...

Enabling Multi-Row Form Submission in jQuery: Ensure Submit Button is Disabled Until Every Row Has a Checked

I am dealing with a multi-row form that contains single choice radio buttons in each row. My goal is to have the final <button> tag disabled until a radio button has been checked in each row. Although I have found a solution from a previous question ...

Tips for effectively sifting through your news feed

I have developed a Chrome extension that extracts newsfeeds from social media pages. However, I want to ensure that posts from specific social media accounts that users follow are kept without injecting but rather filtering them. The challenge lies in the ...

Escaping quotes in JavaScript

After receiving a JSON object in the following format: result: { image: "..." title: "text text \"text\"" } I am currently utilizing underscore.js to render the template, but I am encountering an issue where the title displays with the escape ...

How can I access the data variables from a JSON request within a function?

My task involves loading multiple JSON files from an array called bunchOfData, with each file having a corresponding URL. How can I access my variable "myI" within the processData function? for(var i = 0; i < bunchOfData.length; i++){ $.getJS ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Is it possible to change the src attribute after the page has loaded and execute it

A. I'm trying to figure out how to dynamically change the src attribute of an image using JavaScript after the page has loaded. <img src="http://example.com/image.png" /> to <img src="http://domain.com/different.jpg" /> B. Another questi ...

Execute multiple AJAX calls to continuously update the results for the end user

I am looking to implement a technique using AJAX and PHP to constantly update the browser results. The goal is to dynamically add HTML files to a designated div with the ID results, each representing one of 21 different cities. Rather than displaying all c ...

Tips for sharing CSS from CSS module as a prop in Next.js

I am having trouble applying CSS to a component called Cards. Specifically, I want to style the #image_div div. Below is my code snippet: team.module.css: .grid_container{ display: grid; grid-template-columns: repeat(3,auto); } .image #image_div{ ...

Function in jQuery to reference two different divs

I'm currently facing an issue with a code snippet that I have. The requirement is for the user to be able to hover over "Div 1" and/or "Div2" and trigger a red border around both elements simultaneously. Due to the complexity of my WordPress theme, th ...

What is the process for including a scope in an Angular.js HTTP controller?

I am looking to access a $scope variable within this controller in order to utilize Angular functions like ng-click and ng-change in my HTML. Currently, I am only able to use the $http function but unable to execute any Angular methods on it. I am struggli ...

Conceal Child Component Element Upon onClick Event with ReactJS

As someone new to React, I am learning by coding. Currently, I have component A which includes a select element with menu items (all material UI). Is it possible for the whole component to disappear once a user chooses an option from the dropdown? Essentia ...