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

Exploring the power of Express.js by utilizing local variables and rendering dynamic views

I am in the final stages of completing an application using node.js and express, even though I am still relatively new to them. Here's my situation: In my app.js file, I have declared a variable app.locals.webLang and set its initial value to "EN". T ...

How can we best store the component's state in the URL in AngularJS?

I am working with a reusable widget that has its own state. This state includes the content of the search bar (2), one or more select boxes (1), and the tree where the user can pick the currently active element (3). My goal is to create a locationManager ...

Exploring the concept of union return types in TypeScript

Hello, I am facing an issue while trying to incorporate TypeScript in a way that may not be its intended use. I have created a custom hook called useGet in React which can return one of the following types: type Response<T> = [T, false, false] | [nul ...

Transmit Array of Preferred Values to Controller in MVC Framework

After setting up a view with a search box and buttons labeled "Add" (btn-default) and "Edit" (breadcrumb), I encountered an issue when attempting to pass selected values from the search box to another controller upon clicking the Edit button. Unfortunately ...

Arranging buttons that are generated dynamically in a vertical alignment

Currently, I am in the process of creating a webpage for various items, and everything is going well so far. However, I have encountered an issue while attempting to vertically align the buttons that I am generating using JavaScript within the document. I ...

What is the process for adding submitted data to an already-existing local JSON file?

I have a new Angular assignment that requires me to push form data into an existing JSON file locally. The task is to develop an Angular application where users can create new tasks and view them on a separate page. Initially, I attempted using http.post ...

Need help resolving validation errors in vee-validate?

Is there a way to remove all the errors generated by vee-validate when signing out? The following code does not seem to work, as the form errors are still displaying. Why is that? sign_out: function (e) { console.log('sign me out') var s ...

What is the correct method to choose an element in jQuery based on the function's id parameter

I'm having trouble deleting an item in my to-do list app. deleteToDoItem: function(id) { $(id).remove(); console.log(id); }, Here is the function that calls deleteToDoItem: function deleteItem(event) { var itemID, splitID, t ...

Having trouble getting your Ajax script to function correctly when submitting a form?

I am currently facing an issue where I am loading a partial page, but I do not want the form on this page to redirect when the save button is clicked. I am unsure if I am using the script correctly. I would like to post to the controller when the submit b ...

Warning: When VueJs OnMount props is utilized, it might display a message stating, "Expected Object, received Undefined."

This is my current component setup: <template> <Grid :items="items" /> </template> <script setup> import { ref, onMounted } from 'vue' import Grid from '@/components/Grid.vue' import { getData ...

Unable to send information to a function (using jQuery)

I'm struggling to pass the result successfully to another function, as it keeps returning an undefined value: function tagCustomer(email, tags) { var o = new Object(); o.tags = tags; o.email = email; o.current_tags = getCustomerTags(email ...

I'm looking for a solution to enable the execution of 'expandRowByClick' only when clicking on a specific area within the row in Ant Design. Any suggestions?

In my quest to create a expandable table row with Ant Design's built-in expandRowByClick function, I encountered a dilemma. The function allows me to expand a row by clicking anywhere in it, but what if I want this feature to apply only to a specific ...

Search for documents in MongoDB where two fields have the same value, using $match and $eq

How can I retrieve all documents in a collection where the value of document.a is equal to the value of document.b? I attempted db.collection.aggregate([ { $match: { $eq: [ '$a', '$b' ] } }]) However, this query does not produce any ...

Creating types for React.ComponentType<P> in Material-UI using TypeScript

I am currently working with Typescript and incorporating Material-UI into my project. I am trying to define the component type for a variable as shown below: import MoreVert from '@material-ui/icons/MoreVert' import { SvgIconProps } from '@ ...

Determining the optimal number of rows and columns based on an integer value

Here's a brain teaser for you: /** * Let's figure out the optimal number of rows and columns for your garden to be as square as possible, based on the number of seeds you have. * * @param {number} seedCount - The total number of seeds in you ...

Filter prices (minimum and maximum) using a dropdown menu in asp.net core

Struggling to filter prices using javascript and asp.net core, I've written a lot of javascript code that isn't quite cutting it. I'm wondering if there's a simpler way to achieve this, perhaps with jquery or in c#? If anyone has any ...

Mastering the Art of Mocking DOM Methods with Jest

What is the best way to simulate this code snippet using Jest : useEffect(() => { document .getElementById('firstname') ?.querySelector('input-field') ?.setAttribute('type', &apos ...

Refrain the output of a v-for loop in vueJS

Seeking a simple solution - I have a list of members that I need to iterate through using v-for. However, I only want to display the first two results. Is there a way to limit the displayed results to just the first 2? members = [ {id : 1, name: 'Fran ...

Best practices for utilizing Async/Await in Node 8: A comprehensive guide

With node version 8, async/await becomes available, making code linear for the first time in nodejs natively. This is a nice improvement. In the past, many articles claimed that functions with try/catch blocks were not optimized in the v8 javascript engi ...

Is it possible for the Chrome mobile camera to take up the full screen size on

Currently, I am using the code below to access the camera and display the stream. The width of the element is 100%, but the height seems to be around 70%. Is there a better way to make it fill the entire screen? HTML <video autoplay class="screen"> ...