Vue 3 TypeScript not updating property following API request

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>

Answer №1

To correct the issue, update blogPosts!: BlogPostModel[] to blogPosts: BlogPostModel[] = []

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing the forEach method for decision-making

Here is an array called 'array' with values [10, 15, 20] var array = [10, 15, 20]; There is also a variable named N with a value of 20: var N = 20; I need to iterate through the array and check if N is greater than all numbers in the array in ...

Showing data from a MySql database using an HTML table

I am currently working on a pop-up form that captures user data and stores it in a MySQL phpmyadmin table. My goal is to have this data displayed in an HTML table once the popup form is closed. After submitting the form, I am redirected back to the homepag ...

When using momentJs to add days, it will return a moment object rather than a

How can I add 7 days to a date using momentJs in my Angular project? let startDate = "2018-08-16T02:00:00.242Z"; let newDate = moment(startDate).add(7, 'days'); I was expecting to receive the date after adding 7 days, but instead I get a momen ...

What potential factors could lead to an MUI Snackbar failing to produce the accurate class names?

I am facing an issue with displaying notifications on my Gatsby blog whenever the service worker updates. I am using a MUI Snackbar toast for this purpose. However, sometimes the styling of the toast is not applied correctly and it ends up looking like thi ...

What are the steps to create a Node.js application and publish it on a local LAN without using Nodemon?

When working on a Node.js application, I often use the following commands to build and serve it locally: //package.json "build": "react-scripts build", To serve it on my local LAN, I typically use: serve -s build However, I have been wondering how I ...

Endless Loop Issue with jQuery AJAX Request

I've been working on a project where I'm trying to display data from a Mysqli database using jQuery ajax. However, no matter how much I tweak the code, I always end up in an infinite loop. Has anyone else encountered a similar situation when maki ...

What is the process for integrating a Browserify library module into a project as a standard file?

I have successfully developed a JavaScript library module with browserify --standalone, passing all tests using npm test. Now, I am working on creating a demo application that will utilize this library module in a browser setting. When I run npm update, th ...

Tips for aligning actions to the right of a Vue3 Quasar horizontal card

Looking for help on getting the actions aligned to the far right side while keeping a small title using Quasar classes or Flexbox. When I try replacing the text on the right, it shifts the actions over which is not what I want. https://i.sstatic.net/nECR3 ...

What is the importance of using mutations, setters, and getters for effectively managing state?

As I delve into the world of state management in Vue.js, I am finding it to be quite complex and confusing with all the different methods such as mutations, getters, and setters. Why can't we just change data directly? Wouldn't that make the code ...

Having various ng-apps within a single parent app

Exploring angularjs for the first time and experimenting with multiple ng-apps on a single page. For example, having app2 inside app1 and app1 within rootApp. controller1 includes an $http service that retrieves id and name values and assigns them to $roo ...

The implementation of a Like Button in Django using JS and DOM resulted in a 404 error

I am facing an issue with the 'live' like/unlike button functionality in Django and JavaScript DOM Upon clicking the button, an error is triggered POST http://127.0.0.1:8000/like/24 404 (Not Found) likePost @ javascripts.js:24 (anonymous) @ java ...

Track the number of button clicks on the website without ever resetting the count

Hello there! I have a fun idea for my website - it will have a button that, when clicked 5 times, displays the number 5. Even if you refresh the page or load it again, it should still show 5 and allow you to keep clicking. I can create a counter for one ...

What is the best way to organize the Firebase data that is stored under the user's unique

Hey there, I'm currently working on developing a leaderboard feature for an app. The idea is that users will be able to store their "points" in a Firebase database, linked to their unique user ID. This is how the data is structured in JSON format: ...

Tips for disabling rotation of a glTF model in three.js

I need some assistance with creating a jewelry AR try-on experience using Jeeliz Facetracking and Three.js. The face tracking and model tracking are functioning correctly, but I am facing an issue where the gltf model/scene rotates based on head rotation ...

Understanding Typescript typings and npm packages can greatly improve your development workflow

I'm pleased to see that NPM has now included support for importing TypeScript type wrappers. However, I've noticed inconsistency in how these wrappers are maintained. For instance, when attempting to import "node-git" and "@types/node-git", I fou ...

Transform gradient backgrounds as the mouse moves

I'm attempting to create a unique gradient effect based on the cursor position. The code below successfully changes the background color of the document body using $(document.body).css('background','rgb('+rgb.join(',')+&a ...

ServiceStack request without the use of quotation marks in the JSON body

Why do quotes appear in my request body in Fiddler, but not in my ServiceStack request field? POST http://10.255.1.180:8087/testvariables/new/ HTTP/1.1 Host: 10.255.1.180:8087 Connection: keep-alive Content-Length: 162 Origin: http://10.255.1.180:8087 Use ...

ReactJS Components failing to load on initial site visit, only appearing after refreshing for the second time

var img; var dateFormat = require('dateformat'); var count; let arrayIMG = [] var storage = firebase.storage(); var storeRef = storage.ref('images/') const config = { ... }; if (!firebase.apps. ...

Cypress - Mastering negative lookaheads in Regular Expressions

While experimenting with Cypress, I encountered an issue regarding a filter test. The goal is to verify that once the filter is removed, the search results should display values that were filtered out earlier. My attempt to achieve this scenario involves ...

Using LINQ with ngFor in Angular 6

Within the component.ts, I extract 15 different lookup list values and assign each one to a list, which is then bound to the corresponding <select> element in the HTML. This process functions correctly. Is there a method to streamline this code for ...