WARNING: Rendering error occurred - "TypeError: Unable to access 'text' property as it is undefined"

Trying to add an object to the tags array after making an axios post, but encountering an error when pushing the object.

[Vue warn]: Error in render: "TypeError: Cannot read property 'text' of undefined"

Why is this happening?

I apologize if my question is not clear as I am still a beginner.

Initially, everything was working fine, but after some changes, it stopped working.

I'm not using 'text' anywhere.

javascript/packs/index_vue.js

new Vue ({
    el: '#tags',
    methods: {
~~~~~~~~~~omit~~~~~~~~~~~
      addTag: function(){
        this.submitting = true;
        const newTag = {
          tag: {
            title: this.newTagTitle,
            status: 0,
            tasks: []
          }
        }
        axios.post('/api/tags', newTag)
          .then((res) => {
            console.log('just created a tag')
            //error occurring here
            this.tags.push(newTag);  
            this.newTagTitle = '';
            this.submitting = false;
            this.showNewTagForm = false;
          }).catch(error => {
            console.log(error);
          });
      },
      addTask: function(tagId, i) { // added by edit
        const newTask = {
          task: {
            text: this.newTaskTextItems[i].text,
            deadline: this.newTaskDeadlineItems[i].deadline,
            priority: this.newTaskPriorityItems[i].selected
          },
          tag_task_connection: {
            tag_id: tagId
          }
        }
        axios.post('/api/task/create', newTask)
          .then(() => {
            console.log('just created a task')
            newTask.task.limit = Math.ceil((parseDate(this.newTaskDeadlineItems[i].deadline).getTime() - new Date().getTime())/(1000*60*60*24));
            this.tags[i].tasks.push(newTask.task);
            this.newTaskTextItems[i].text = '',
            this.newTaskDeadlineItems[i].deadline = '',
            this.newTaskPriorityItems[i].selected = '',
            newTask.tasks = '',
            newTask.tag_task_connection = ''
          }).catch(error => {
            console.log(error);
        });
      }
~~~~~~~~~~omit~~~~~~~~~~~
    },
    mounted: function () {
      axios.get('/api/tags')
      .then( res => {
        this.tags = res.data.tags,
        this.newTaskTextItems = res.data.newTaskTextItems,
        this.newTaskDeadlineItems = res.data.newTaskDeadlineItems,
        this.newTaskPriorityItems = res.data.newTaskPriorityItems,
        this.checkedItems = res.data.checkedItems
      })
    },
    data: {
      tags: [],
      options: [
        { name: "Low", id: 1 },
        { name: "Medium", id: 2 },
        { name: "High", id: 3 }
      ],
      showNewTagForm: false,
      showStatusFrom: false,
      changeStatusTag: 0,
      deleteConf: false,
      deleteTarget: 0,
      helloWorld: false,
      firstModal: true,
      newTagTitle: '',
      loading: false,
      submitting: false,
      newTaskTextItems: '',
      newTaskDeadlineItems: '',
      newTaskPriorityItems: ''
    }
~~~~~~~~~~omit~~~~~~~~~~~
})

views/tags/index.html.slim

routes.rb

controllers/api/tag_controller.rb

models/tag.rb

views/api/tags/index.json.jbuilder

I made some changes to the code, but the same error persists.

In index_vue.js:

this.tags.push(newTag);

this.tags.push('something');

When doing this, no error occurs. Is push() incorrect?

this.tags.push('something');

console.log(this.tags) // this.tags.push('something');

Answer №1

Make sure to include this line whenever you are defining text:

 content: this.newTaskTextItems[i] ?  this.newTaskTextItems[i].text : ' ';

This will help prevent any errors from occurring. Additionally, consider using console.log(this.newTaskTextItems, this.newTaskTextItems[i], i) to check for undefined values, as some may be present while others are valid.

Answer №2

I successfully addressed the issue.

addTag: function(){
  this.submitting = true;
  const newTag = {
    tag: {
      title: this.newTagTitle,
      status: 1,
      tasks: [],
      errors: {
        text: '',
        deadline: '',
        priority: ''
      }
    }
  }
  axios.post('/api/tags', newTag)
    .then(() => {
      console.log('tag creation successful')
      this.submitting = false;
      this.showNewTagForm = false;
      this.newTagTitle = '';
      if (this.errors != '') {
        this.errors = ''
      }
      var newTaskTextItem = {text: ''};
      var newTaskDeadlineItem = {deadline: ''};
      var newTaskPriorityItem = {selected: 0};
      this.newTaskTextItems.push(newTaskTextItem); //I got the error, because I hadn't been doing this.
      this.newTaskDeadlineItems.push(newTaskDeadlineItem);
      this.newTaskPriorityItems.push(newTaskPriorityItem);
      this.tags.push(newTag.tag);
    }).catch(error => {
      if (error.response.data && error.response.data.errors) {
        this.errors = error.response.data.errors;
      }
      this.submitting = false;
      this.showNewTagForm = false;
    });
},

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

The ng-repeat function is iterating through the array multiple times

Using ng-repeat to bind the same array multiple times. JavaScript : $scope.currentitem = item; $scope.currentitemCategory = $scope.currentitem.category.split(','); console.log($scope.currentitemCategory); HTML: <div ng-repea ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Getting the header component in home.vue within Vue.js: A step-by-step guide

Is there a way to hide a button in the header by using JavaScript to access the component inside Home.vue? I've attempted to retrieve the element ID of the button within Home.vue, but it remains unattainable. ...

Visibility issue in Three.js: Object not appearing immediately despite setting object.visible to true

I'm toggling visibility in my Three.js scene by using the .visible property on objects. Initially, certain objects (rooms) have their .visible property set to false. Once the camera enters a specific mesh (the room bounding box), the .visible propert ...

Uncaught ReferenceError: The variable in Next.JS is not defined

Within the server-side code of page.tsx, I have a client-side component called SelectType.tsx. The functionality should be as follows: When the user changes the value of the select component It triggers a function inside page.tsx The function is supposed ...

Hide the menu when a user clicks on any of its options

On a next.js website, there is a hidden panel that slides out from the edge when a button is clicked. Inside the panel, there is a menu. The panel and the menu are separate components. The goal is to have the panel open and close when the button is clicked ...

Why does the ng-click function fail to execute when using the onclick attribute in AngularJS?

Whenever I try to invoke the ng-click function using onClick, I encounter an issue where the ng-click function is not being called. However, in my scenario, the model does open with the onClick function. //Function in Controller $scope.editProductDetail ...

React dynamically updating table with a fresh layout

With my React component, I've innovatively designed a block format for presenting To-Dos at a Pet Store. This allows users to categorize and organize their tasks in blocks rather than a simple list of unorganized To-Dos. The functionality of adding a ...

Reasons Behind Slow Unmounting of React Components

In my current project, I have implemented a component that wraps multiple ReactList components. The ReactList component features infinite scrolling, meaning it only loads what is currently in the viewport. There are two modes available - simple and uniform ...

CSharp MVC using HTML input field styled with Bootstrap features

I have set up a textbox on my webpage which prompts the user to input a string. Upon pressing a button, this string is compared to find matching fields in the database. Additionally, I have another button that triggers the display of a bootstrap modal wher ...

The Controller in Angular.js is initialized after the view is loaded

I am facing an issue where I need to return the URL of each ID I receive, but the URL is being generated asynchronously. This delay in generation is causing a problem as I am unable to display it on the view immediately. How can I make the code wait unti ...

Encountering a ReferenceError while debugging MongoDB: The console object is undefined

Using a js file within mongodb, I implemented a code snippet containing a console.log expression for debugging purposes: use test; db.city.find().snapshot().forEach(function(city){ var Pos = city.Pos; if (Pos) { longLat = Pos.split(" ...

Is it possible that event.returnvalue=false is causing issues in Firefox?

Currently, I am updating an outdated application to ensure it works seamlessly on Firefox. Since the original application does not utilize Jquery, I need to rely solely on Javascript for all my modifications. One of the tasks involves restricting input in ...

The phenomenon of jQuery AJAX converting the escape character from %20 to + has been observed

I am encountering an issue with my jQuery AJAX function which is supposed to save an image path to the database. Below is an example parameter: var data = {}; data['url'] = "Path%20to%20URL"; Normally, if there is a space or %20, it sh ...

Upgrade minimist is available

Recently, an error message has been appearing on my GitHub account: Upgrade minimist to version 0.2.1 High severity Vulnerable versions: < 0.2.1 Patched version: 0.2.1 Minimist before 1.2.2 could be manipulated into adding or changing properties of O ...

Creating precise squares in JavaScript and animating their movement at designated intervals

My goal for the Final Project is to create a JavaScript-based game similar to Guitar Hero, but with squares instead of circles representing the notes. In Guitar Hero, players have to hit the notes at specific times. I am facing a challenge in my code wher ...

Utilize titles and hrefs for images in an array of objects

In my Canvas, there is a map as the background image with markers placed in different cities. These markers are images duplicated from an Array of Objects and added to the Canvas using drawImage(). Now, I need to include href and title attributes in these ...

Tips on utilizing imacros for extracting image URLs

I am currently experimenting with the use of imacross for web scraping, but I have encountered a roadblock when it comes to extracting image URLs from markdown code like the one provided below. <div class="dpimages-icons-box"> <a href="http: ...

The server encountered a 500 Internal Server Error because it could not read the 'username' property of an undefined object

When attempting to register a user in a mongodb database using express, a POST call was made to localhost:3000/users/register The request body included: { "firstName": "Jason", "lastName": "Watmore", "username": "jason", "email": "<a ...

Discover the elements with Protractor, cycle through the total number of located elements, and proceed to press the button

Trying to figure out how to click a button multiple times based on the number of elements found with a specific classname. If there are 3 elements found, the button should be clicked 3 times. The current approach: (Update at the bottom) The total count ...