VueJS: Unable to access the 'name' property as it is undefined"

I'm at a loss trying to figure out a solution for this issue. My current task involves editing a pub schedule using an edit form:

pubs/UpdateProfile.vue

<template>

<confirm title="Edit Pub" ok="Save pub" :show="show"
         v-on:save="save"
         v-on:close="close">

    <div class="field">
        <label class="label">Name</label>
        <div class="control">
            <input class="input" type="text" placeholder="Pub name" v-model="data.name">
        </div>
    </div>

    <!-- Other fields and functionalities omitted for brevity -->

</confirm>

<script>

    import Pub from "../../models/pub";

    export default {

        data() {
            return {
               selected: null,
               data: new Pub(),
            }
        },

        props: {
            show: Boolean,
            data: Object,
        },

        computed: {

        },

        methods: {
            save() {
               this.$emit('save', this.data);
            },
            close() {
                this.$emit('close');
            },

            // Functionality methods omitted for brevity

            updateOpeningTime(schedule){
                this.api.put('/pubschedules/' + this.data.id + '/' + schedule).then(response => {
                    this.data = response.data;
                });
            }, 
        }
    }
}

In my controller:

PubsController.php

public function updateOpeningTime(Pub $pub)
{
    json_die("Hola");

    json_die($pub->id);

    Schedule::where(['pub_id', $pub->id])->update(['opening_time' => request()->all()]);
}

pub.js

export default class Pub {

constructor() {
    this.id = null;
    this.name = null;
    this.schedulesDisplayed = null;
  }
};

schedulesDisplayed is sourced from a relation between Pub and Schedule models (pubSchedules: 1pub x N schedules):

/**
 * @return \Illuminate\Database\Eloquent\Collection
 */
public function getSchedulesDisplayedAttribute()
{
    return $this->pubSchedules()->get();
}

Upon clicking the Save button post-editing, I can see the "Hola" message invoked in the controller. However, I encounter errors preventing further development with the following error messages:

app.js:56802 [Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"

found in

---> <UpdateProfile> at 
resources/assets/js/components/pubs/UpdateProfile.vue
   <Pubs> at resources/assets/js/components/Pubs.vue
     <Root>

The error points towards a 'name' property that seems to be missing or improperly referenced. Any insights into resolving this issue will be greatly appreciated.

Answer №1

To properly update your opening time, refactor your `updateOpeningTime` function as shown below:

updateOpeningTime(updatedSchedule) {
    let self = this;

    this.api.put('/pubschedules/' + this.data.id, updatedSchedule).then(response => {
        self.data = response.data;
    });
}

If you don't use `self` inside the API call's `then` method, `this` will not refer to the correct component instance.

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

Sending a JavaScript variable to a Flask url_for function

There is an endpoint that requires a value in the URL and then generates content to be displayed within a specific div. I'm trying to construct the URL using url_for with a JavaScript variable, but it seems that $variable1 is being treated as a string ...

Encountering an issue with postman where properties of undefined cannot be read

I am facing an issue while trying to create a user in my database through the signup process. When I manually enter the data in the create method, it works fine as shown below: Note: The schema components are {userName:String , number:String , email:Stri ...

Retrieving the value of a specific property nested within a JSON object using basic JavaScript

Hey there! Thanks for taking the time to check out my question. I'm diving into JavaScript and I've hit a roadblock trying to solve this particular problem: I'm looking to extract the value of a property nested within a JSON object under a ...

Maintaining AngularJS Authentication Securengular: Ensuring

I need to find the ideal architectural solution. Below is the HTML code I currently have: <body ng-controller="individualFootprintController as $ctrl"> <div ng-hide="$ctrl.authenticated"> <h1>Login</h1> Wit ...

Selenium and PhantomJS are having trouble interpreting JavaScript code

Currently experimenting with Selenium and PhantomJS for Java search tasks, I'm facing an issue where PhantomJS fails to activate javascript. My goal is to access a webpage that utilizes javascript. Previously, this method worked well for me, but now I ...

Incorporate CloudKit JS into Vue Application

I want to integrate CloudKit JS into my new Vue project so I can access its functions from any component within my app. As a newcomer to Vue, I appreciate your patience with me. :) Currently, I attempted adding the following code snippet in main.js: var ...

A useful Javascript function to wrap a string in <mark> tags within an HTML document

I have a paragraph that I can edit. I need to highlight certain words in this paragraph based on the JSON response I get from another page. Here's an example of the response: HTML: <p id="area" contenteditable> </p> <button class="bt ...

Using assets in data property or methods in Vue 3 with Vite - how to efficiently manage and access resources

Recently delving into Vue 3 and vite, I've encountered a peculiar issue during production build. In development, everything runs smoothly but when I switch to production, the assets defined in the data property are inexplicably ignored, leading to a 4 ...

Steps for implementing Onclick event within the <Script> tag to display a div:

I am currently working on a code that allows me to show and hide a <div> element after clicking on an advertisement from any website. This advertisement is generated by a script. How can I implement the onclick event within the <script> tag? T ...

What is the best way to determine which section of a promise chain is responsible for an error in Javascript?

(Please excuse any errors in my English) I am currently studying JavaScript promises. Below is a simple JavaScript code snippet for node.js (using node.js version v10.0.0) that asynchronously reads and parses a JSON file using promise chaining. const fs ...

Is there a way to work around coursera's keyboard input verification using JavaScript?

Is it possible to bypass Coursera's keyboard input verification using JavaScript? For example: What methods or techniques could be used to accomplish this? ...

Dealing with PhantomJS: Tackling the Challenge of XMLHttpRequest Exception 101 Error

As a newcomer to JavaScript and PhantomJS, I have been encountering an issue when running myfile.js (which involves for loops) with the command phantomjs myfile.js. It consistently throws the error: NETWORK_ERR: XMLHttpRequest Exception 101: A network err ...

Omit a specific page from the primary Next.js layout within the application directory

In my project, I have a main layout file located at /app/layout.tsx and separate authentication pages. I want the authentication pages to have their own custom layout defined in the file /app/auth/layout.tsx. The issue I am facing is that the main layout ...

Tips on sending a form to the server with ajax technology

I'm struggling with sending a button id to my server through ajax in order to submit a form without having to constantly reload the page every time I click on a button. Unfortunately, it's not working as expected and I can't figure out why. ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

Angular 2 System.config map leading to a 404 error message

I am encountering a 404 error in the browser console while attempting to map the Auth0 module from node_modules in my Angular 2 project using the system.config in the index file. Index File <!-- 2. Configure SystemJS --> <script> System.con ...

The update feature seems to be malfunctioning within the MEAN Stack environment, specifically with node.js and angular js

Looking for some assistance as a beginner in the mean stack. I'm trying to update a record using the update function, but it's not working as expected. I need to update a specific object based on its ID, however, I'm encountering issues wit ...

Storing data from an API response into the localStorage using Vue.js upon clicking

My objective is to save specific data in the browser's localStorage upon clicking a link. However, the output I receive is either undefined or completely empty. <li v-for="(category, index) in categories" :key="index"> ...

Locate a specific class inside a div and switch the CSS style to hide one element and reveal another

I have two divs, each containing a span. By default, the display of each span class is set to none. My goal is to toggle the display property of the span within the clicked div. If the span is already visible, I want to hide it; if it's hidden, I want ...

Failed to cast value "undefined" to ObjectId in the "_id" path for the model "User"

I've been encountering an issue that I can't seem to resolve despite searching on Stack and Google. My ProfileScreen.js is meant to display a user's profile, but when attempting to view the profile, I receive this error: "Cast to ObjectId fa ...