Issues encountered while modifying Vue data

In my Vue JS 2 code, I have structured my data as follows:

data : {
          newBus: {
            name: '',
            hours: {
              sunday: '',
            }
          }
        }
        

When setting the data using this input field:

<input v-model="newBus.hours.sunday" type="text" placeholder="Sunday">
        

Adding a business in this way is successful. However, when attempting to update the data by clicking on an item from a list and having the saved data fill the form, the following method is used:

<div v-for="bus in businesses" v-on:click="editBus(bus)" class="list-group-item bus-list-item">{{bus.name}}</div>
        

The editBus() method encounters the error:

vue.js:1453 TypeError: Cannot read property 'sunday' of undefined

This issue arises immediately upon clicking the item for updating. Any suggestions on how to tackle this?

EDIT: It seems that the error is linked to the absence of the hours property in the bus object. When checking with console.log(bus), it does not display. How can I incorporate this data into the business object without causing errors? It's puzzling because if it were not nested - i.e., sunday: '' instead of hours: { sunday: ''} - it functions correctly.

EDIT: For reference, here is the recreation on CodePen.

Answer №1

The issue at hand is more of a Javascript problem rather than a Vue problem. You cannot access a property of undefined.

Let's consider the data structure in your code sample.

newComment: {
    name: '',
    comment: '',
    votes:  0,
    time:  timeStamp(),
    subcomment: {
        name: ''
    }
}

In this scenario, you have set up all values with defined placeholders, so everything should work smoothly. The problem arises when you click on the edit button, and the received object appears as below:

{
    name: "some name",
    comment: "some comment",
    time: "4/5/2017",
    votes: 145,
    .key: "-Kh0PVK9_2p1oYmzWEjJ"
}

It's crucial to note that there is no subcomment property present here. This leads to the following results when trying to access this code:

newComment.subcomment

which evaluates to undefined. However, in your template, you proceed to reference:

newComment.subcomment.name

Therefore, you are attempting to retrieve the name property of undefined, resulting in an error being thrown.

To prevent this error, one approach is to ensure that the subcomment property exists before rendering the element using v-if:

input#name(type="text")(placeholder="Name")(v-model="newComment.subcomment.name")(v-if="newComment.subcomment")

This will help avoid the error from occurring.

Alternatively, within your editComment method, you could verify if subcomment exists, and if not, add it:

if (!comment.subcomment)
    comment.subcomment = {name: ''}
this.newComment = comment

Lastly, why does it work with non-nested data? The key distinction lies in this: if newComment exists in the form of

newComment: {}

and you attempt to access newComment.name, the result will be undefined. If your template includes something like v-model="newComment.name", no crashes will occur; it will simply set the input value to undefined and update accordingly.

Essentially, when referencing newComment.subcomment.name, you are targeting a property of a nonexistent entity, whereas with newComment.name, the object itself exists without the name property.

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

Tips on retrieving PHP variable values along with HTML response using AJAX in PHP

I am looking to retrieve 2 variables: 1) The total number of records from the mysqli query performed in search_members.php 2) A boolean value indicating whether any results were found Below is the code I have written: <input type="button" value="Sea ...

Exploring ways to expand a field in Laravel Nova

Recently, I have been working with Laravel Nova and am trying to develop a custom field inspired by BelongsToMany. The plan is to start with the existing code for this field and then incorporate my modifications. I attempted to create a custom field and e ...

Callback is triggered after ng-if removes the directive from the scope

A scenario on my page involves an angular directive nested within ng-if. I've developed a service that features a function, let's name it functionX, capable of accepting a callback as an argument. Whenever the ng-if condition becomes true, the ...

Tips for updating a specific field within an object in an array within a mongoose schema and persisting the changes

I am currently developing a website where users can sign in, create tasks, and mark them as done. I am using mongoose to work with the data, specifically saving tasks inside an array of type Task in a User model. Each task has a "done" value which is repre ...

Is it possible to implement Vue2 components within a Vue3 environment?

Recently, I've built a collection of Vue2 components that I've been using across multiple projects through a private npm repository. Now, as I begin a new project in Vue3, I'm wondering if it's feasible to incorporate the old components ...

Expiration Alert: SSL Certificates for HERE Links will expire shortly

Our SSL certificates for the following URL's are approaching expiration: *.base.maps.ls.hereapi.com geocoder.ls.hereapi.com Do you have any information on when these URLs will be updated with new certificates? ...

Ensure that all asynchronous code within the class constructor finishes executing before any class methods are invoked

Looking to create a class that takes a filename as a parameter in the constructor, loads the file using XmlHttpRequest, and stores the result in a class variable. The problem arises with the asynchronous nature of request.onreadystatechange, causing the ge ...

Configure environment variables for either grunt or grunt-exec

Attempting to utilize grunt-exec for executing a javascript test runner while passing in a deployed link variable. This is being done by initializing an environment variable grunt.option('link') with the help of exec:setLink. Within my test_runn ...

Switching languages in Nuxt i18n causes the data object to reset

Recently, I incorporated nuxt-i18n into a project to support multiple languages. Everything was running smoothly until I encountered an issue where switching language while filling out a form resulted in all data on the page being lost. To tackle this pro ...

Developing a personalized language setting in Nuxt.js for internationalization

I'm facing an issue with my application where I am struggling to figure out how to create a custom locale. For example, I have routes like /hello and /ja/hello, where the first route is for the default English language and the second one is for Japane ...

Error: Material UI search bar doesn't refresh interface

I implemented Material UI's auto complete component to create a dynamic select input that can be searched. The component is fed options in the form of an array consisting of strings representing all possible choices. <Grid item xs = {props.xs} cla ...

Is it better to include the Google Analytics code in the master page or on every individual page of an asp.net

Looking for a way to track every page on my website effectively. Should I insert the Analytics tracking code in each aspx page inherited from the master page, or is it sufficient to place it only in the master page to track all inherited pages? ...

Is it possible to modify the color of a division row using an onchange event in JQuery?

I am facing a requirement to dynamically change the color of rows based on the dropdown onchange value. The rows are structured in divisions, which were previously tables. There are two main divisions with rows that need to be updated based on dropdown sel ...

Send the form using an alternative method to avoid using preventDefault

Having some trouble with my website's sign-in functionality not working properly on all browsers. In Firefox, I keep getting a "ReferenceError: event is not defined" error. I've read through various posts about preventDefault behaving differentl ...

I am encountering difficulties with generating images on canvas within an Angular environment

I am trying to crop a part of a video that is being played after the user clicks on it. However, I am encountering the following error: ERROR DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may no ...

When trying to load a php page2 into page1 via ajax, the Javascript code fails to execute

Currently, I am in the process of learning PHP and JavaScript. I have encountered a particular issue with a webpage setup. Let's say I have a page called page1 which consists of two input fields and a button labeled 'Go'. Upon clicking the & ...

Using plain JavaScript, adding an element to an array by pushing the value of a string variable in an index position rather than pushing the

I have the following JavaScript code snippet: let array = []; const datas = [ 'name1', 'name2', 'name3', ]; async function getData() { datas.forEach((data) => { let myData = data.name; if(!array.include ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

Explanation of TypeScript typings for JavaScript libraries API

Currently, I am in the process of building an Express.js application using TypeScript. By installing @types and referring to various resources, I managed to create a functional program. However, my main query revolves around locating comprehensive document ...