Encountering a TypeError in VueJS - Trying to access undefined properties when deleting or adding Sensor information

In my VueJS application, I am attempting to dynamically create a sensorArray. However, when I create an element, delete it, and then try to create a new one, I encounter the following error:

client.js:227 TypeError: Cannot read properties of undefined (reading 'value')
    at eval (templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./pages/Test.vue?vue&type=template&id=cde3d4aa&:44)
    at Proxy.renderList (vue.runtime.esm.js:2643)

Below is a snippet of my simple Vuejs application:

<template>
  <div>
    <span>Sensor Information : </span>
    <button class="btn btn-info" @click="addSensorInfo($event)">
      Add Sensor
    </button>
    <br>
    <span v-if="sensorArray.length > 0"><b>Sensor Element: </b></span>
    <span v-if="sensorArray.length > 0">&nbsp;&nbsp;
      <div v-for="sensor in sensorArray" :key="sensor.ID" class="form-group">
        <label class="form-label">Value</label>&nbsp;&nbsp;
        <input v-model="sensorArray[sensor.ID].value" type="text" class="form-control">
        <button class="btn btn-danger" @click="deleteSensorInfo($event,sensor.ID)"><i class="bi bi-trash" /></button>
      </div>
    </span>
  </div>
</template>

<script>
export default {
  data () {
    return {
      sensorID: 0,
      sensorArray: []
    }
  },
  methods: {
    addSensorInfo (event) {
      event.preventDefault()
      const sensor = {}
      sensor.ID = this.sensorID
      this.sensorArray.push(sensor)
      this.sensorID++
    },
    deleteSensorInfo (event, sensorID) {
      event.preventDefault()
      this.sensorArray.splice(this.sensorArray.filter(obj => obj.ID === sensorID), 1)
    }
  }
}
</script>
  1. Click on Add Sensor button: A text field and delete button will appear.
  2. Click on Delete ICON and delete the field.
  3. Now click on Add Sensor again and I receive the following error:
client.js:227 TypeError: Cannot read properties of undefined (reading 'value')

Since I have many elements within my SensorArray, I am not creating dedicated elements and instead trying to create everything dynamically based on user clicks. Can someone please advise me on how to resolve this issue?

Answer №1

Initial Mistake

The operation you are trying to perform is not valid in JavaScript.

this.sensorArray.splice(this.sensorArray.filter(obj => obj.ID === sensorID), 1)

When using the splice method, you need to provide a number at the first position.

splice(start: number, deleteCount: number)

Additionally, the filter method returns an array.

Solution

const idx = this.sensorArray.findIndex(obj => obj.ID === sensorID);
if (idx !== -1) {
    this.sensorArray.splice(idx, 1)
}

Alternatively, you can use a more concise approach:

this.sensorArray = this.sensorArray.filter(obj => obj.ID === sensorID);

Next Issue

I've noticed an incorrect array access in your code. The array should be indexed by "id," not the custom "sensor.ID." The expression 'sensorArray[sensor.ID].value' does not make sense and only works before deletion due to ID generation logic.

Here's the corrected code snippet with proper usage of `v-model="sensor.value"`:

<div v-for="sensor in sensorArray" :key="sensor.ID" class="form-group">
    <label class="form-label">Value</label>  
    <input v-model="sensor.value" type="text" class="form-control">
    <button class="btn btn-danger" @click="deleteSensorInfo($event,sensor.ID)"><i class="bi bi-trash" /></button>
</div>

Lastly, ensure that the property '.value' is properly set in your data structure.

Answer №2

To remove an item, it's important to differentiate between splice and filter. For deletion, it is recommended to utilize filter.

this.updatedArray = this.originalArray.filter(item => item.ID === targetID);

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

Create an ASP button with drag and drop functionality

Is there a way to enable drag and drop functionality for an asp:Button element? Also, how can I retrieve the coordinates of the button after implementing jquery drag and drop? My goal is to store these coordinates in a database so that when I revisit the ...

Troubleshooting the lack of response in ASP.Net MVC when utilizing OfficeOpenXml for a new Excel file creation

Situation I have encountered an issue while generating an Excel file using OfficeOpenXml in C#. The generated file is not being returned to the browser. Any thoughts on why this might be happening? Code Snippets [C#] : public ActionResult ExportToExcel( ...

Is it possible to dynamically include custom attributes to a Vue component element?

I am looking to develop a component in Vue that can accept any arbitrary attributes (such as data-xxx) from Vue.data at run-time, without the component expecting or knowing about them. For example, even though this code snippet does not work, the concept i ...

Tips for accessing data in Vue.js pug templates:

Essentially, my goal is to create a permalink from an event name. I am able to retrieve the value from the event name using v-model successfully, but I'm having trouble figuring out how to input the converted permalink into another input box in pug. ...

What is the proper way to access an element from the state within a foreach loop in Vuex?

Currently in my Vue application, I'm utilizing Vuex. Within the store, there is an object declared like so: state: { list: { a: false, b: false, c: false } } In the mutations section, there ...

Unable to assign values using Promises in an Angular component

While working on a Component HTML file, I encountered an issue with exposing a variable. The variable was supposed to retrieve a value from the response using cl.getMonitors. Strangely, despite seeing console.dir(res) in the console, the value of the var ...

Is there a reason why I can't load all Google charts on one webpage?

I am trying to use the Google Charts API to display various charts on my web page. However, I seem to be encountering an issue where the last chart is not loading correctly. Can someone point out what I might be missing in my code? I would greatly apprecia ...

Guide to attaching a class to the parent element upon checkbox verification using Vue.js version 2.0

Can we add a class to the parent div based on the checked state of a checkbox? If not, what is the alternative method? Take a look at the code snippet below: <div class="checkbox-container" v-for="item in items" :key=" ...

Ensuring the proper sequence of operations within a jQuery ajax callback function

I am facing an issue with my jQuery ajax function. The callback function includes two actions: 1) Taking the ajax result (which is an html form) and inserting it as the inner html of an html span. 2) Submitting this form How can I make sure that the form ...

Retrieving embedded documents from Mongoose collections

I am currently facing challenges in caching friends from social media in the user's document. Initially, I attempted to clear out the existing friends cache and replace it with fresh data fetched from the social media platform. However, I encountered ...

The react transition group fails to add the necessary CSS classes to the specified div

Regardless of whether I utilize React transition group, Tailwind, pure CSS, or any other framework, no transitions seem to occur when I structure my simple component in the following manner. I have experimented with various frameworks, but the outcome rema ...

Instructions for sending React form information to a database.json file using axios on a local server

I'm having trouble figuring out how to transfer the input data from my form to my JSON file on my localhost. The form in HTML collects a name, title, and content. The objective is to utilize the form to generate a new article, send that form data to t ...

Counting on AngularJS that is nested within ng-repeat

I need help figuring out how to count the number of 'td' elements generated in a loop. Using $index isn't working for me because it resets on each row, causing confusion with setting 'i' for each iteration. What is the best and si ...

Tips for utilizing the date-formatter feature of bootstrap-table with Angular 2

Hello there! I have integrated the bootstrap-table library with Angular4, but I am facing an issue with the date-formatter feature. Here is the HTML code snippet: <table id="table" data-show-refresh="true" data-show-toggle="true" data-show-columns="tr ...

Error: Cannot access the 'top' property of an undefined object

Here is a snippet of my jQuery code: $(document).ready(function(){ $('.content-nav a').on('click',function(){ var str = $(this).attr("href"); var the_id = str.substr(1); $("#container").animate({ scrollTop: $ ...

Utilizing vuetifyjs: Selectively incorporating necessary icons into the build

I am currently working on a vuetifyjs-app using the default "Material Design Icons". For the production build, I am only utilizing 2 icons from this font (which are being used by the vuetify-component chips). Following recommendations, I have included the ...

a class instance in Java Script returned as undefined

Having sought resolution for this question once before, I find myself revisiting it as the issue still persists. My apologies for the duplicate post. The first file in question is block.js: class Block{ constructor(timeStamp, lastBlockHash, thisBloc ...

Encountering an error of "undefined is not iterable, cannot read property Symbol(Symbol.iterator)"

While learning React through coding, I encountered an error (Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)). I am unsure where the problem lies. Any suggestions? When utilizing useEffect to activate setFiltere ...

Is there a way to leverage the useSWR hook for making numerous requests simultaneously?

I am attempting to utilize the useSWR hook for multiple calls, but I keep encountering an error message that reads: Cannot read properties of null (reading 'destroy') async function FetchApi(url) { const response = await fetch(url); const ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...