[Vuejs]-VueJS getting TypeError: Cannot read properties of undefined when I delete and add an Sensor information

2👍

First Error

This is not a valid JavaScript operation

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

Splice signature expects a number at first position

splice(start: number, deleteCount: number)

Filter signature returns an array.

Solution

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

Or as mentioned you can use a more concise form

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

Second Error

Now I noticed that you are performing a strange array access. An array is indexed by id not by your custom sensor.ID, so this sensorArray[sensor.ID].value makes no sense. It works before a delete by pure chance (due to how you are generating IDs).

This should be your code (note the v-model="sensor.value"):

<div v-for="sensor in sensorArray" :key="sensor.ID" class="form-group">
    <label class="form-label">Value</label>&nbsp;&nbsp;
    <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>

Furthermore .value is never set.

0👍

You are mixing up splice and filter, to delete the item.
Simply use filter.

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

Leave a comment