Vue.js - Difficulty displaying fetched data from API using v-for

My attempt to render a list of data seems to be hitting a roadblock - the data doesn't display when the page loads. The API call works perfectly, fetching all the necessary data and setting it to my data object. Here's the code snippet: once 'blogPosts' is set, it becomes an array of objects.

<template>
<div>
    <div class="bw-blog-card" v-for="post in blogPosts" :key="post.id">
        <div class="bw-blog-card__profile"></div>
        <div class="bw-top-blog__top-card">
            <div>
            creator: {{ post.username }}
            </div>
            <div>
                {{ post.created_at }}
            </div>
            <div class="bw-blog-card__card-title">
                {{ post.title }}
            </div>
            <div>
                {{ post.description }}
            </div>
        </div>
    </div>
</div>
</template>

<script>
module.exports = {
    data: () => {
        return {
            blogPosts: []
        }
    },
    methods: {
        getBlogPosts: async () => {
            try {
                let { data } = await axios.get(`/devblog`)
                this.blogPosts = data.data
                console.log(this.blogPosts)
            }
            catch (error) {
                console.error(error)
            }
        }
    },
    created() {
        this.getBlogPosts();
    }
}
</script>

If I manually assign 'blogPosts' as an array of objects, everything works fine. Any idea why it's not working when fetched through an API call?

Answer №1

Consider updating getBlogPosts: async () => { to async getBlogPosts() { for a potential solution :

Vue.config.devtools = false;
Vue.config.productionTip = false;

let app = new Vue({

  el: '#app',

  data() {
    return {
      blogPosts: []
    }
  },
  methods: {
    async getBlogPosts() {
      try {
        let {
          data
        } = await axios.get(`https://jsonplaceholder.typicode.com/posts`)
        this.blogPosts = data
        console.log(this.blogPosts)
      } catch (error) {
        console.error(error)
      }
    }
  },
  created() {
    this.getBlogPosts();
  }

})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ff9faeacfbda1f7">[email protected]</a>/dist/vue.js"></script>

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="app">
  <div class="bw-blog-card" v-for="post in blogPosts" :key="post.id">
    <div class="bw-blog-card__profile"></div>
    <div class="bw-top-blog__top-card">
      <div>
        creator: {{ post.userId }}
      </div>

      <div class="bw-blog-card__card-title">
        {{ post.title }}
      </div>
      <hr/>
    </div>
  </div>
</div>

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

Issue: Vue.js is not recognizing the proxy configuration in vue.config.js file

I have tried extensively to find a solution to this issue by searching and reading through various documentation, but unfortunately, I have been unable to make it work. You can find more information on the topic at https://cli.vuejs.org/config/#devserver-p ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

Transmission of JSON to a C# controller via AJAX results in a Count value of zero in .NET 7

Whenever I attempt to send a JSON object to my controller, the parameter isn't being received. This is the JavaScript code snippet: var input = document.getElementById("input"); input.addEventListener('change', function () { const read ...

Is it possible to conduct a comparison between two arrays by utilizing a computed property in Vue.js?

Apologies if my explanation was not clear. I am trying to implement an edit amenity feature similar to Airbnb. I have an array called "Amenity" which stores id and name values. I then loaded all the amenities for house_id = 2 into an array named "house_am ...

The custom select component is failing to update its value

I'm facing an issue with a component that has the following code: <template> <select class=" py-1.5 px-2 outline-none border-primary-lightblue border-2 rounded-xl transition duration-500 ...

Implement a formatter function to manipulate the JSON data retrieved from a REST API within the BootstrapVue framework

My bootstrap-vue vue.js v2.6 app is receiving JSON data from a REST API. The data structure looks like this: { "fields": [ { "key": "name", "label": "name", & ...

Mastering the art of using either promises or callbacks properly

Attempting to retrieve the result of a variable after completing all asynchronous processes in a function. I've discovered that I need to use promises for this, so I spent today learning about them. I've implemented promises in my function and c ...

How do I make a component in React delete itself from a page when its internal state changes?

For instance: {!loading ? (data.map((v, i) => { return <Card key={i} title={v.name} image={v.pictures.sizes[4].link}} /> }) These cards are displayed as a series of components on the main screen. Each card ...

Discover a method to receive an alert when the mouse exits the inner window along the y-axis

Is there a way to receive an alert if the mouse moves out of the inner window solely in the y-axis? Currently, alerts are triggered when the mouse moves out on both x-axis and y-axis. For example, if the mouse pointer hovers over the address bar coming fro ...

Updating the content of a window without the need to refresh the page using JavaScript

Is there a way to navigate back to the previous window in chat_user without refreshing the entire page when the back button is clicked? Below is the code I have tried: <a href="" onclick="window.history.go(-1); return false;">back</a> ...

Typescript polymorphism allows for the ability to create various

Take a look at the following code snippet: class Salutation { message: string; constructor(text: string) { this.message = text; } greet() { return "Bonjour, " + this.message; } } class Greetings extends Salutation { ...

Top method for creating a checkbox filter to toggle the display of elements depending on various data-* attributes

I am currently working on creating a checkbox filter that will display or hide elements based on multiple data attributes assigned to those elements. Despite my attempts, I have not been able to achieve the desired filtering outcome. You can view a basic ...

Learn how to hide elements on print pages conditionally in Vue.js using CSS or JavaScript

I am currently using the Vue framework to work on printing webpages for my application. I have an issue that needs a solution, which I will explain below. <template> <div id = "intro" style = "text-align:center;"> <div ...

Unlock the power of Angular JS to display dynamic content effortlessly

My experience with AngularJs is very limited. In one of my projects, I need to display dynamic content on a page that changes based on the database values retrieved via an HTTP GET request. Before implementing the entire functionality, I decided to test i ...

"My PHP headers are not working properly when I try to

When I invoke a script with JavaScript var user = document.getElementById('username').value; var pass = document.getElementById('password').value; var conf = document.getElementById('confirm').value; var code ...

What is the predefined value for a multi-select generated by the ng-for directive in Angular?

I am having trouble setting default selected values for the multi-select. Despite trying various methods such as initializing the ngModel to bind the variable and using [selected] = "selectedSegment == 'S1'", none of them seem to be effective fo ...

Ensure consistency across browsers by disabling zoom functionality on touchpad inputs while still permitting scrolling actions

I am looking for a way to disable 2-finger zoom on trackpad "wheel" events while still allowing 2-finger scroll. On mobile, I have already disabled zoom with: <meta name="viewport" content="initial-scale=1, minimum-scale=1, m ...

Attempting to limit entry to a pathway when the loggedIn criterion is satisfied

I am currently facing a challenge with restricting access to the login page if the user is already logged in. I have been attempting to achieve this by checking for an existing token in the localStorage. Do you have any suggestions on how I can troublesh ...

What is the method for React to tap into the local variables of Hooks functions?

Here we have a basic hook example function App() { let [counter, setCounter] = useState(0); return <button onClick={() => setCounter(counter + 1)}>{counter}</button>; } My understanding of React operation is: React will invoke App() to ...

Show Zeroes in Front of Input Numbers

I am working with two input fields that represent hours and minutes separately. <input type="number" min="0" max="24" step="1" value="00" class="hours"> <input type="number" min="0" max="0.60" step="0.01" value="00" class="minutes"> This se ...