Aniki
Aniki

Reputation: 386

Vue 3 typescript wont update property after api call

I have api on node js and call it wit vue. When I call it i and get the results i parse it and try to push it on property in the class so it can be passed down to a component but the property is undefined and get this error.

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push')

This is the code.

<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>

Upvotes: 0

Views: 525

Answers (1)

Aniki
Aniki

Reputation: 386

Fix by changing blogPosts!: BlogPostModel[] to blogPosts: BlogPostModel[] = []

Upvotes: 1

Related Questions