I am new to Vuejs and would need some help, please. I am calling a component in order to create a ‘member’. While calling this component and passing the member data, the component raises an error related to one of the functions inside. The issue seems that the member data is not being initially fulfilled considering that the member data is being fetched via an API. I have tried converting the function which causes the error to Asynchronous but that does not seem to work either. Below please find some code snippets for my issue.
Home.vue
<Member :member="memb" />
data() {
return {
memb: {},
};
},
//Method fetching the member from api
async fetchMember(memberId) {
const res = await axios.get(`http://localhost:3000/members/${memberId}`, { apiHeaders });
return res.data;
},
//Method which fetched the member
async created() {
this.memb = await this.fetchMember(1);
},
Member.vue
<template>
<div class="m-auto">
<p>Name: {{ member.name }}</p>
<p>Surname: {{ member.surname }}</p>
<p>Date of Birth: {{ formatDob(member.dob) }}</p>
<p>Age: {{ calculateAge(member.dob) }}</p>
<p>Relationship: {{ member.relationship }}</p>
<button class="bg-blue-500 py-1 px-4 rounded-md text-gray-100 text-sm mx-1 mt-3 font-bold" @click="$emit('get-member-id', member.id)">Update</button>
<button class="bg-red-500 py-1 px-4 rounded-md text-gray-100 text-sm mx-1 mt-3 font-bold" @click="$emit('delete-member', member.id)">Delete</button>
</div>
</template>
<script>
export default {
name: 'Member',
props: {
member: Object,
},
methods: {
// Converting the date of birth format
formatDob(dob) {
return dob.split('/').reverse().join('/');
},
// Calculating the date of birth by comparing today's date with the member's date of birth
calculateAge(dob) {
const birthdate = new Date(dob);
const todayDate = new Date();
const difference = todayDate - birthdate; // This is the difference in milliseconds
return Math.floor(difference / 31557600000);
},
},
};
</script>
The issue that I am getting is related to calling the formatDOB from the Member component. In fact the issue says: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘split’)
Thanks in advance.
>Solution :
- Will be cool if we can implement a progress indicator meant for informing the users about loading activity of data
- Once the member data loads, you can start showing the member component and hide the progress indicator.
- Pseudocode would look like something below.
<Member v-if="isLoaded" :member="memb" />
<ProgressBar v-if="!isLoaded" />
<script>
export default {
data: (() => {
return {
isLoaded: false,
memb: null
}
})
async mounted() {
this.isLoaded = false;
this.memb = await this.fetchMember(1);
this.isLoaded = true;
}
}
</script>