So I have a small problem but maybe some of you can help me. I'm using Axios to fetch data with my Rest API and put the data (bookings) into an array. In the template I want the name of the of the desk instead of the Id, so I need to call a method which compare the id's and return the number.
There is the problem. It says this in the console: "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id')".
But the weird thing is that it works. The message only pop-up one time (while the v-for generates around 15 items). I could just ignore the error message but I think something isn't working in the background. I think the problem is that the "getRightDesk"-method gets called before the Array "desks" get filled with data.
In the Template:
<template>
<tbody>
<tr v-for="data in api" :key="data.id" :item="data">
<td>{{ data.id }}</td>
<td>{{ desks[getRightDesk(data)].description }}</td>
<!-- Calling the method here -->
<td>{{ format_date(data.start) }} Uhr</td>
<td>{{ format_date(data.end) }} Uhr</td>
<td >
<div >
<button
@click="updateDate(data), editBooking(data)"
>
Bearbeiten
</button>
</div>
<div >
<button @click="doDelete(data.id)">
Löschen
</button>
</div>
</td>
</tr>
</tbody>
</template>
Important script parts:
<script>
import axios from 'axios'
export default {
name: 'BookingElements',
data() {
return {
api: [],
url: 'https://localhost:7052/api/',
start: '',
end: '',
bookingId: '',
deskId: '',
desks: [],
}
},
methods: {
getBooking() {
axios
.get(this.url 'booking', {
headers: {
Authorization: 'Bearer ' this.$store.state.token,
},
})
.then((response) => {
this.api = response.data
})
.catch((error) => console.log(error))
},
getDesks() {
axios
.get(this.url 'desk', {
headers: {
Authorization: 'Bearer ' this.$store.state.token,
},
})
.then((response) => {
this.desks = response.data
})
.catch((error) => console.log(error))
},
getRightDesk(data) {
let rightDesk = false
let number = 0
while (rightDesk == false) {
if (this.desks[number].id == data.deskId) {
// Here is the error message
rightDesk = true
return number
} else {
number
}
}
},
format_date(value) {
if (value) {
return moment(String(value)).format('DD.MM.YYYY | HH:mm')
}
},
mounted() {
this.getBooking()
this.getDesks()
},
},
}
</script>
Please ignore the bad code-writing-skills, I'm beginner
CodePudding user response:
Few things that improved OP's code fixed the issues:
- wrapping
tr
inside of a<div v-if="api">
- using
async/await
across all functions - using filter rather than a
while