In my Vue.js application, I have several components that are structured similarly and are all throwing the same error:
TypeError: Cannot read property 'id' of undefined
I initially attempted to resolve this issue by enclosing {{ jobs[0].id }}
within a <template :v-if="jobs">
or
<template :v-if="jobs[0].id">
, as suggested in other StackOverflow posts. However, this did not eliminate the errors. Interestingly, despite the console displaying the 'undefined' property error, all data, including the 'id', is rendered on the page without any missing values. Nonetheless, my unit tests continue to fail with the same error.
<template>
<div class="emptyDiv">
<h3>
Latest Build -
<router-link:to="{name: 'job_details'}">
{{ jobs[0].id }}
</router-link>
</h3>
</div>
<template>
<script>
export default {
name: "Stages",
data() {
return {
jobs: []
};
},
created() {
this.JobExecEndpoint =
process.env.VUE_APP_TEST_URL +
"/api/v2/job/"
fetch(this.JobExecEndpoint)
.then(response => response.json())
.then(body => {
this.cleanStartTime = moment(body[0].time_start);
this.cleanEndTime = moment(body[0].time_end);
this.cleanDuration = this.calculateDuration(
this.cleanStartTime,
this.cleanEndTime
);
this.jobs.push({
name: body[0].job.name,
id: body[0].id,
env: body[0].job.env,
time_start: this.cleanStartTime.format("LLL"),
time_end: this.cleanEndTime.format("LLL"),
duration: this.cleanDuration,
status: body[0].status.name,
job: body[0].job,
});
})
.catch(err => {
console.log("Error Fetching:", this.JobExecEndpoint, err);
return { failure: this.JobExecEndpoint, reason: err };
});
}
};
</script>
After spending extensive time troubleshooting for about 10 hours, I managed to resolve the errors and pass my unit tests by adding the following code snippet within the 'created' block:
.then(() => {
this.new_id = this.jobs[0].id
})
I also included new_id=''
under the data section and referenced new_id
in the template. However, although this workaround solved the immediate problem, it is not an ideal solution since I am still unsure why the original code triggered the error and whether it would work correctly with a complete array (containing more than one job).