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

Calculate the total length of the nested arrays within an object

Check out this object: const obj = { name: "abc", arr: [{ key1: "value1", arr1: [1, 2, 3] }, { key1: "value2", arr1: [4, 5, 6] }] } I'm looking to find a way to quickly calculate the sum of lengths of arrays arr1 and arr2. ...

Vue.js filtering by number

Looking to implement filtering in a Vue project. I have an input field that currently filters by store name extracted from a JSON object, which includes both the store name and ID as a number. How can I also filter by store ID? computed: { filtered ...

JQuery Falters in Responding to Button's Click Action

Forgive me for what may seem like a silly question, but as someone new to JQuery, I have been struggling to figure out why my function is not displaying an alert when the button is clicked. Despite thorough research on Google, I haven't been able to f ...

"Utilize the inline display property to keep elements hidden

I have created a template named 'aTemplate' using the following code: $.template('aTemplate', '<div id="someid" class="abc">' + .... '</div>' ); My goal is to make this div inline with other ele ...

group array by month and year

I have an array structured like this var dataset = [[1411151400000,1686],[1428604200000,1686],[1411151400000,1686]....] The goal is to group the data based on months and calculate the total sum of values for each month. The expected final output should ...

Header Overflow Error Encountered in Node.js GET Request

While attempting to programmatically submit a form through Google forms using a GET request, I encountered the error message Parse Error: Header overflow. The debug code output is as follows: REQUEST { uri: 'https://docs.google.com/forms/d/e/9dSLQ ...

Guide to refreshing extensive dataset using MySQL migration scripts

We are in the process of developing a Nodejs application for a client who has requested that we use migration scripts to streamline updating the production database. As someone new to MySQL, I am struggling with how to update table contents using only MySQ ...

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

Sharing specific props with deeply nested components in React

I am experimenting with configuring props for children components. In this example, I am testing a function to target any child, whether nested or not, with the prop swipeMe. It works perfectly when the render function contains only a single child, like ...

Obtain information stored locally when an internet connection is established

I'm currently facing an issue with my Local Storage data retrieval process in Vuejs while being online. My ToDo app setup consists of Vuejs, Laravel, and MySQL. When the internet connection is available, I store data in localStorage. The ToDo app has ...

Are you experiencing issues with modal contents extending beyond the modal on smaller screens?

I recently installed a modal plugin called blockUI for my image uploading needs. Although I have styled and positioned everything accordingly, I am facing an issue: Whenever I resize the browser screen, switch to my iPhone, or use another screen, some con ...

The recently added item in nestedSortable remains stationary and does not shift positions

const menu = $("ol.menu").nestedSortable({ handle: '.move', items: 'li', placeholder: 'placeholder', opacity: 0.7, toleranceElement: '> i', c ...

Tips for Utilizing PHP Without the Need to Refresh the Page

Below are the contents of three files with their respective code: Controler.php <iframe id="frame1" style="display:none"></iframe> <iframe id="frame2" style="display:none"></iframe> <button onClick="document.getElementById(&apo ...

Filtering with multiple attributes in Angular using GroupBy

I have a set of JSON data structured like this: [ { "id": 1, "address": "MG Road", "country": INDIA, "state": AP, "city": VIJ }, { "id": 2, "address": "Miyapur", "country": INDIA, ...

The de-duplication feature in webpack is not functioning properly when the splitChunks cacheGroups commons option is activated

In my lerna project, I have two identical packages named p1 and p2. Both p1 and p2 utilize a 3rd party package - in this case, eosjs@beta, which is approximately 50KB in size. When I incorporate p1 into an example react project, the package size increase ...

Encountered difficulties sending JSON data to a REST endpoint using Node.js

Is there a way to bulk insert JSON data into MongoDB using Mongoose? I am aware of the insertMany method, but I'm encountering difficulties with extracting the correct req.body. Below is an image of my setup in Postman. https://i.sstatic.net/xFznd.pn ...

What is the best way to access the child DOM of a Vue element?

Is there a way to access the child DOM element of a Vue component? In the code snippet below, I am trying to retrieve the <input> element nested within the <div>. var vm = new Vue({ el: '#box', data: { pick: true, a: & ...

Unravel the JSON structure

Here is the JSON response I received from an AJAX call: [{"id":null,"period":null,"until":null,"agent_id":"15","agent_zlecajacy_id":"15","offer_id":null,"status":"1","tytul":"Pobranie ksi\u0105g","tresc":"Pobranie ksi\u0105g","data_aktualizacji" ...

JavaScript function to add or subtract

I need to include additional inputs for "+ and -" 60mm and 120mm in my function. How can I achieve this without turning all of them into separate functions? <template> <card class="card"> <h2>Measurement</h2> <form&g ...

Mapbox GL JS stops displaying layers once a specific zoom level or distance threshold is reached

My map is using mapbox-gl and consists of only two layers: a marker and a circle that is centered on a specific point. The distance is dynamic, based on a predefined distance in meters. The issue I'm facing is that as I zoom in and move away from the ...