Unable to retrieve information from v-for as it returns null data

Currently facing an issue with retrieving data from the database using Axios in Vue.js. I am able to see the data in my database through Vue.js developer tools like this: https://i.stack.imgur.com/n7BRO.png

However, when attempting to loop through the data using v-for, as shown below:

<template>
    <div class="flex flex-col items-center py-4">
        <NewPost></NewPost>
        <Post v-for="(post,i) in posts.data" :post="post" :key="i"/>
    </div>
</template>

<script>
import NewPost from "../components/NewPost";
import Post from "../components/Post";
export default {
    name: "Newsfeed",
    components: {
        NewPost,
        Post
    },

    data: () => {
        return {
            posts: null
        }
    },

    mounted() {
        axios.get('/api/posts').then(res => {
            this.posts = res.data
            console.log(this.posts)
        }).catch(error => {
            console.log('Unable to fetch posts')
        })
    }
}
</script>

<style scoped>

</style>

The console is displaying the following error message:

"[Vue warn]: Error in render: "TypeError: Cannot read property 'data' of null"

found in

---> at resources/js/views/Newsfeed.vue at resources/js/components/App.vue "

I am confused because I can see the data in Vue.js developer tools. Could there be an issue with the looping method? Any help would be greatly appreciated. Thank you!

Answer №1

Starting out with a blank array for the nested field is important, as shown below:

    data: () => {
        return {
            entries: {
                   elements:[]
                 }
        }
    },

Answer №2

One possible solution is to include a loading variable in the data section like so:

Within the data method:

data: () => { return { posts: null, loading: true } }

Inside the mounted hook:

mounted() {
        axios.get('/api/posts').then(res => {
            this.posts = res.data
            this.loading = false
            console.log(this.posts)
        }).catch(error => {
            this.loading = false
            console.log('Failed to retrieve posts')
        })
    }

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 RapidAPI in VBA Excel: Discovering Domain Name Ownership

I've come across some other discussions on the same topic, but I haven't been able to find a clear answer. I would really appreciate it if someone could assist me with this problem. I'm trying to integrate RapidAPI into my VBA code in Excel ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

VITE: "Unable to load URL" message encountered when working with a Vue single file component

I am encountering an issue with my VUE application bundled with vite when loading dependencies as vue single file components. The setup follows the standard scaffolded vite example. Below is my vite.config.js: import { fileURLToPath, URL } from 'node ...

Creating a structure for data in Ruby on Rails to facilitate AJAX calls to controller actions

I am in need of a button on my website that can send data to the create action of a controller named "pagetimes". The functionality seems to be partially working, but it is not sending all the specified data. This issue may be due to my inability to struct ...

Unlocking $refs with the Composition API in Vue3 - A step-by-step guide

I am currently exploring how to access $refs in Vue 3 using the Composition API. In my template, I have two child components and I specifically need to obtain a reference to one of them: <template> <comp-foo /> <comp-bar ref="ta ...

Exploring the Scope of HTML Element IDs within Vue Components

Does Vue provide a built-in scoping mechanism for components so that the id attribute values of HTML elements inside each component are automatically unique? In the code snippet below, I have created two components and expected them to behave independentl ...

What is the functionality of the toArray method?

var retrieveDocs = function (db, callback) { var collection = db.collection('tours'); collection.find({ "tourPackage": "Snowboard Cali" }).toArray(function (err, data) { console.log(data); callback; }) } Is there a p ...

How can Selenium in Python be used to click a JavaScript button?

I need help automating the click of a button on a webpage using selenium Here is the HTML for the button: <div class="wdpv_vote_up "> <input value="7787" type="hidden"> <input class="wdpv_blog_id" value="1" type="hidden"> </div& ...

Adding an image to a Select Option label in React: A simple guide

As a newcomer to React, I am experimenting with creating a drop-down menu that includes images in the labels. My approach involves using a function to gather values from a map and construct an id: label pair to display as options in the drop-down. Both the ...

Unpredictable hovering actions when interacting with nested items within the hover layer

Imagine a scenario where we have the following elements: A container that holds everything A baseDiv inside that container // Let's create a base layer var container = document.getElementById('container') var baseDiv = document.createEl ...

When Index.html is hosted via Express, the component fails to render

Following a tutorial has led me to the end and I've made changes to my App.js as shown below: import React, { Component } from "react"; import "./App.css"; class App extends Component { render() { return ( <div> <p>lm ...

Interacting with an API and retrieving data using JavaScript

I have hit a roadblock. This question might be simple, but I am struggling to figure it out. I am attempting to retrieve a response from an API (mapquest), but I can't seem to navigate the response to extract the necessary information. Here is my con ...

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...

Issue in Babel: The preset 'latest' could not be located in the directory even though it was installed globally

I executed a global installation of Babel using: npm install -g babel-cli npm install -g babel-preset-latest Although it is generally not recommended to install Babel globally, I find it preferable in order to maintain a clean directory structure without ...

Using ajax to submit variables may not function properly

I have a set of data that has been processed using JavaScript and I am looking to save it to a database. I have been attempting to code something with AJAX, but so far, I have had no success... What I require: Two variables (id, name) need to be sent to a ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...

Design my div layout to resemble a tree shape

Take a look at this URL. I have dynamically created divs in a nested structure for a sports tournament. I need help styling the divs to match the tournament structure. This is how I want my structure to look. The code is functioning properly, it's ju ...

ajax call triggering knockout foreach update

Within my ViewModel, I have defined a variable called self = this; Another foreach binding is working in my code, but it is not within an ajax request. The initial UI load is functioning correctly. I have confirmed that self.wikiData is being updated by ...

Using VueJS to assign data within a method function

Below is the HTML code that I have written: <div id="myApp"> <div class="items"> <div class="item" v-for="quiz in quizzes" :key="quiz.id"} <span>{{ quiz.question }}</span> <span v-if="selected[quiz. ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...