When iterating over slice objects in a JSON file using v-for in Vue, a warning is triggered: TypeError - Attempting to access property 'slice' of

I received a JSON response from a Laravel API containing 800 items. The challenge is to display only 15 items to the user initially, with an option to load more by clicking on a 'Load More' button.

Although everything seems to be functioning correctly, Vue Js throws a warning message:

[Vue warn]: Error in render: "TypeError: Cannot read property 'slice' of undefined"

Here is the code snippet where the issue arises:

<div class="col" v-for="value in products.products.slice(0, productsShow)">
//logic {{value.content}}
</div>
<button 
v-if="products.products.length > 15 && 
productsShow < products.products.length" 
@click="loadMore">
Load more products
</button>

VueJs

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                products: [],
                productsShow: ''
            }
        },
        methods: {
            loadMore () {
                this.productsShow += 15
            }
        },

        created() {
            axios.get('/api/products/pt').then(response => this.products = response.data)
            this.productsShow = 15
        }
    }
</script>

Alternative attempt:

<script>
    import axios from 'axios'
    export default {
        data() {
            return {
                products: [],
                productsShow: 15
            }
        },
        methods: {
            loadMore () {
                this.productsShow += 15
            }
        },

        created() {
            axios.get('/api/products/pt').then(response => this.products = response.data)
        }
    }
</script>

Edit API response can be viewed here: View Laravel API Response

Answer №1

The reason for the issue is due to instantiating products as an array when it should actually be an object with the property 'products'. To resolve this, make sure your data declarations are structured like this:

 export default {
    data() {
        return {
            products: {
                products: []
            },
            productsShow: 15
        }
    }
}

Additionally, in your template, you can make the following changes.

<div
    class="col"
    v-if="products.products"
    v-for="value in products.products.slice( 0, productsShow)"
>

You can use either of these methods to fix the issue.

Answer №2

Verify that the response you are returning is in JSON format, not PHP. Make sure your API endpoint includes something similar to this: return response()->json($response);

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

How can you directly specify/change a JavaScript function in Java Selenium and execute it within a browser?

Let me tell you a story... In my school, there's an online poll where different dorms are competing for a special prize. What started as a simple vote quickly turned into a coding challenge. Using Selenium Chromedriver, I was able to automate clicking ...

verification of access that is beyond the control of the web user

Important Information about the Web User Control: <asp:CustomValidator ID="cvServerValidateDate" runat="server" ControlToValidate="tbDate" onservervalidate="cvValidateServer" ValidateEmptyText="True" ClientValidationFunction="validateDateCo ...

Error: The iOS 14.2 system is unable to locate the variable "webkit."

Currently, I am developing a web application using AngularJS 1.7. The app runs smoothly on Safari with iOS versions 12, 14.0, and 14.1. However, upon upgrading my iOS to version 14.2/14.3 (tested on both), I encountered the following error: Error: Referen ...

What could be causing the CSS to not display properly on specific routes?

I'm facing an issue where CSS seems to be working fine for certain routes with node.js & express, but not for others. It's puzzling because the HTML file links to the same CSS file in both cases. For instance, CSS works perfectly for the route " ...

`Is there a way to modify the zAxis of a Paper component in Material-UI?`

Hello, I am curious about how to change the z-axis of a paper from MUI. https://i.sstatic.net/iKXLG.jpg The issue I'm facing is that the carousel is overlapping my menu and I need the menu to be on top of everything. Here is how I have it structure ...

What is the most effective method for identifying duplicate values in a multidimensional array using typescript or javascript?

I have a 2D array as shown below: array = [ [ 1, 1 ], [ 1, 2 ], [ 1, 1 ], [ 2, 3 ] ] I am looking to compare the values in the array indexes to check for duplicates. For example array[0] = [1,1]; array[1] = [1,2]; array[2] = [1,1]; We can see that ...

Switch between different RGB background colors

I'm currently working on a project where I want to toggle the background color from RGB to a solid color. My approach involves using Change inner HTML to switch the background color, but I've been facing some difficulties in getting it to work co ...

Transform JSON data into HTML format while excluding particular values

I recently integrated a JSON API that fetches event data. Here's a snippet of the JSON structure: { "id":1, "status":"ok", "start":{ "date":"2021-01-16" } } To display this ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

Tips for finding documents in MongoDB using query filters

My website features a table where users can enter a word in a search field, prompting mongodb to search for matching words in specific objects and only return those results. The search text is included in the request query. Although the following code han ...

Issue with Jquery FullCalendar when using JSON data, unless the data is hardcoded

Trying to configure the JSON Feed for the Adam Shaw jquery full calendar has been a bit of a challenge. It works smoothly in Chrome, but not so much in FireFox or IE. These browsers seem to have trouble rendering appointments passed as a JSON string unless ...

Why isn't Sequence.js Slider automatically playing?

Issue: The sequence.js slider I implemented is not animating. Despite adding the following options: animateCanvas: true, fadeStepWhenSkipped: false, autoPlay: true, autoPlayInterval, 2000 It still does not work. Is there something essential t ...

Instructions for adding background music to a website page via audio playback

Is there a way to automatically play an audio file when my web page loads on the client's browser? Additionally, can the audio be paused by the user clicking a button on the web page and resumed when desired? ...

Fade out and slide close a div using jQuery

I am creating a new website and incorporating jQuery for animation and simplified JavaScript implementation. My goal is to have a button that, when clicked, will close a div with a fading out and slide up effect. Can this be achieved? Thank you. ...

Is resizing possible using the Canvas identifier?

Is it possible to adjust the canvas size to match the width of the page using the canvas id's style in the html? Then in your javascript code for the canvas, can you have resize listeners that are responsive to the canvas size at any given time? I c ...

Encountering a 'JSON parsing error' while transmitting data from Ajax to Django REST Framework

I've been encountering an issue while trying to send a JSON to my REST API built with Django Rest Framework. Every time I make this request, I receive an error message, regardless of the view I'm accessing. I suspect the problem lies in the AJAX ...

Access language options in the dropdown menu using keyboard shortcuts

I have a dropdown that appears when the mouse hovers over it: Is there a way to also trigger the dropdown to appear when the user tabs to it? I've tried following this thread for guidance: Selecting div in custom dropdown using Keyboard (Up, down and ...

TypeScript is encountering difficulties locating a local directory

I'm currently facing an issue with my Typescript and Node.js project in Visual Studio. The error is related to importing a local folder called "source" into my top-level file, application.ts. However, despite having the necessary directory structure s ...

Unable to process a post request in node js using axios

Whenever I attempt to POST, I consistently receive a "Cannot GET /api/auth/signup" error. I am unable to figure out the reason behind this issue and would greatly appreciate any help. It seems that I am missing something while trying to register in Node.js ...

The Node function is failing to produce a JSON object as expected

This particular file in my library is named verifyToken.js require('dotenv').config(); const CognitoExpress = require("cognito-express"); //Initializing the CognitoExpress constructor const cognitoExpress = new CognitoExpress({ cognitoUserP ...