Working with an API on Node.js and calling it with Vue has presented a challenge for me. After making the call and receiving the results, I attempt to parse them and push them onto a property in the class so they can be passed down to a component. However, I am encountering an issue where the property is undefined and I receive the following error message:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')
Here is the code snippet:
<template>
<div class="home">
<!-- <BlogPostCard v-for="blogPost in blogPosts" :key="blogPost.Id" /> -->
</div>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component'
import BlogPostCard from '@/components/BlogPostCard.vue'
import BlogPostModel from '../models/blogPostModel'
import fetch, { RequestInit } from 'node-fetch'
@Options({
components: {
BlogPostCard
}
})
export default class AllBlogPostsView extends Vue {
blogPosts!: BlogPostModel[]
async beforeMount () {
await this.getPosts()
}
async getPosts () {
const requestOptions: RequestInit = {
method: 'GET',
redirect: 'follow'
}
const response = await fetch('http://localhost:4000/blog/all', requestOptions)
const result = await response.json()
for (let i = 0; i < result.length; i++) {
const blogpost = result[i]
const id: number = blogpost.Id
const title: string = blogpost.Title
const content: string = blogpost.Content
const blogPostModel = new BlogPostModel(id, title, content)
console.log(this.blogPosts)
this.blogPosts.push(blogPostModel)
}
}
}
</script>