Property not valid: expected an array, but received an undefined value

I have a Vue component called Shoes, which utilizes the Products component that in turn uses the Product component. The Products component receives an array from an API to populate the Product component with information.

However, when I attempt to fetch an array from the API within the Shoes component and pass it to the Products component (which expects an Array), Vue throws an error saying it received Undefined. What's going on...

"Shoes" component:

<!-- eslint-disable-next-line -->

<template>
  <div>
    <app-products :new_products="new_products" :old_products="old_products"></app-products>
  </div>
</template>

<script>
    import getData from "../data/get_data";
    
    export default {
        data() {
            return {

            }
        },
        methods: {
            async getShoes () {

                const response = await getData('products', 'shoes');

                const new_products = [],
                    old_products = [];

                for (const product of response.data)
                    product.tag === 'new' ? new_products.push(product) : old_products.push(product);

                console.log(this.products.new, this.products.old);

                this.new_products = new_products;
                this.old_products = old_products;

                console.log(this.products.new, this.products.old);
            }
        },
        async mounted() {
            await this.getShoes()
        }
    }

</script>

<style>

</style>


Products component:

<template>
   <div>
     <div class="wrap wrap_for_new" v-if="new_products.length !== 0">
       <h1 class="write" >These items are now available!</h1>
       <div class="main_wrap">
         <app-product v-for="(product, key) of new_products"  class="new_product" :key="key" :name="product.name" :descriptions="product.description" :price="product.price" :ImageId="product.id" :count="product.count"></app-product>
       </div>
     </div>
     <div class="wrap" v-if="old_products.length !== 0">
       <div class="main_wrap">
         <app-product v-for="(product, key) of old_products" :key="key" :name="product.name" :descriptions="product.description" :price="product.price" :ImageId="product.id" :count="product.count"></app-product>
       </div>
     </div>
   </div>
</template>

<script>
    export default {
        props: {
            new_products: {
                type: Array,
                required: true
            },
            old_products: {
                type: Array,
                required: true
            }
        },
        methods: {
            setGridColumns() {
                let ret_ = '';

                for (let i = 0; i < Math.round(window.innerWidth / 170); i++) {
                    ret_ += '1fr ';
                }

                for (let el of document.querySelectorAll('.main_wrap')) el.style.gridTemplateColumns = ret_;
            },
        },
        async beforeCreate() {

            console.log(this.new_products, this.old_products);

            this.setGridColumns();
        }
    }
</script>

<style>

  .wrap_for_new {
    margin-top: 50px;
  }

  .wrap {
    border-bottom: 1px solid red;
  }

.main_wrap {
  position: relative;
  display: grid;
  height: 100%;
  grid-template-rows: 1fr;
  grid-gap: 5px;
}

  .new_product {
    border: red solid 1px !important;
  }

  .write {
    text-align: center;
    font-size: 150%;
  }

  .red {
    color: red;
  }

  .write span {
    color: red;
  }
</style>


Product component:

<template>

    <div class="product" >

      <div class="look" @click="look">
        View
      </div>

      <img :src="`localhost:8000/image/${ImageId}`" class="image_still"  :alt="`${name} product image`"/>

      <div class="product_name"> {{ name }} </div>

      <div class="descriptions">{{descriptions | toolongtext}}</div>

      <div class="price"> {{price}} </div>

      <div class="count"> {{count}} items </div>

    </div>

</template>
<script>
    import { animate } from '../staticFunctions/animate';
    import emitter from "../../src/main";

    export default {
        props: {
            name: String,
            descriptions: String,
            price: String,
            ImageId: String,
            count: Number
        },
        methods: {
          look() {
              emitter.$emit('look', {
                  name: this.name,
                  descriptions: this.descriptions,
                  price: this.price,
                  ImageId: this.ImageId,
                  count: this.count
              });
              animate('product-look', false);
              this.isOpened = !this.isOpened;
          }
        },
        filters: {
            toolongtext: value => value.length > 51 ? value.slice(0, 51) + '...' : value
        }
    }
</script>

<style scoped>
  .product {
      height: 400px;
    width: 90%;
    background-color: #fafafa;
    box-shadow: 0 0 5px gray;
    margin: 10px;
    border-radius: 10px;
    float: left;
    max-width: 90vw;
    max-height: 90vw;
    display: grid;
    grid-template-rows: 0.5fr 4fr 1fr 2fr 1fr;
    grid-template-columns: 1fr 1fr;
    grid-template-areas:
      "look look"
      "img img"
      "name name"
      "desc desc"
      "prc count";
  }
  .look {
    opacity: 0;
    width: 100%;
    text-align: center;
    grid-area: look;
    transition: opacity 1s;
  }

  .product:hover .look,
  .product:active .look {
    opacity: 0.6;
  }

  .product * {
    text-align: center;
  }

  .descriptions {
    grid-area: desc;
  }

  .image_still {
    grid-area: img;
  }

  .product_name {
    grid-area: name;
  }

  .price {
    grid-area: prc;
  }

  .count {
    grid-area: count;
  }



</style>

Answer №1

Make sure to properly define the variables new_products and old_products within the data section of your Shoes component:

data() {
    return {

    }
},

Currently, you are just assigning values to them without defining them first:

this.new_products = new_products;
this.old_products = old_products;

This will result in them being non-reactive and thus undefined. Be sure to define them like this:

data() {
    return {
        new_products: [],
        old_products: []
    }
},

In addition, remember to stick to either lowerCamcelCase or kebab-case for property naming conventions, avoiding the use of snake_case.

For example:

:new-products="new_products"

Instead of:

:new_products="new_products"

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 PHP for a server-side backup in case the CDN is inaccessible

Looking to simulate some server-side functionality: <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> if (typeof jQuery == 'undefined&apo ...

Using JavaScript to Retrieve Image Sources

function validate(form) { while ($('#img').attr('src')=="../static/img/placeholder.png") { return false; } return true; } ^I'm having trouble with this code. I want my form to prevent submission as long as ...

Pass data from Symfony using an array of objects to a Vue.js component within a Twig template

I am currently working with symfony5 and I want to incorporate vue.js into one of my twig template views. My goal is to pass 3 different Objects to vue.js, each containing multiple Arrays which typically store several Objects. After installing vue.js, here ...

Tips for adjusting image and div sizes dynamically according to the window size

In my quest, the end goal is to craft a simplistic gallery that closely resembles this particular example: EXAMPLE: This sample gallery is created using Flash technology, but I aim to develop mine utilizing HTML, CSS & Javascript to ensure compatibil ...

Updating the value of a $scope variable located within an included template in AngularJS

My setup is quite simple as outlined below. The issue I'm facing is that out of the two variables I define within the $http success callback, only one is reflected in the UI. In this scenario, I am attempting to display progress when the controller l ...

What strategies can I implement to streamline my CSS code and avoid repeating the same styles multiple times within my HTML document?

The input box contains predefined values with unique IDs or generates them based on certain rules. Here is the HTML code: <input class="box" type="text" style="width:8%; text-align:center" id="a" value="A" readonly="true"/> <input class="box" ty ...

Django Ajax not transmitting image data in Ajax call

I'm currently facing an issue while attempting to send data from a popup form through a Django template that includes an image as well. When trying to access the data in the console, it is properly visible. However, when using an AJAX function, no dat ...

What is the best way to utilize JavaScript to determine if a particular word is present in a SharePoint text field, especially when the content of the text box is modified or updated

My SharePoint textfield is displaying strangely, with code that looks like this: <div class="ms-taxonomy-fieldeditor ms-taxonomy-fieldeditor-standard ms-taxonomy-writing" title="Category" style="width: 364px;"> <div id="ctl00_PlaceHolderMain_Ed ...

What is the process for inserting a hyperlink into text within a tooltip?

I have implemented a tooltip within my input field using an external component, as illustrated in the code snippet below. Within the tooltip, I am trying to include a hyperlink so that users can click on the word 'world' and be directed to anothe ...

How do I ensure a single row in my table constantly remains at the bottom?

I am currently working on developing a MUI table that shows rows, with the last row displaying the total number of colors. The challenge I am facing is ensuring that the last row always stays at the bottom when there are no results in the table. I have att ...

Rearrange the order of divs dynamically to prevent wrapping/overflow, no need for media queries

Can someone help me with this issue? I am trying to create a navigation bar with centered menus/links, a logo on the left, and call-to-action buttons and icons on the right. If the content overflows or wraps, I want the center column to move to the next l ...

Trouble obtaining AJAX result using onClick event

As a newbie to AJAX, I am still trying to grasp the concept. My task involves using an AJAX call to extract specified information from an XML file. Even after carefully parsing all tag elements into my JavaScript code, I encounter a problem when attempting ...

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

Encountering a CORS blockage: The request header authorization is restricted by Access-Control-Allow-Headers in the preflight response

I encountered an error message that says: Access to XMLHttpRequest at 'http://localhost:4000/api/investments' from origin 'http://localhost:5000' has been blocked by CORS policy: Request header field authorization is not allowed by Acce ...

The repetition of the react nodejs page load occurs when the get method is utilized

I've successfully set up a page and function for loading the customer list. However, I'm facing an issue where adding the get method to my code results in it being called every time information is received from the URL and the page is rendered. i ...

Tell webpack to exclude a specific import

Currently, I am in the process of developing a desktop application using ElectronJS and ReactJS. To bundle the renderer process that utilizes JSX, I have opted to use webpack. An issue arises when attempting to import anything from electron into the rend ...

The error message reads: `'Icon' is not included in the export list of 'antd'`

I have recently developed a React application and I'm incorporating Ant Design (antd) into it. However, I encountered an issue in one of my project files where I am unable to use the Icon tag. It seems like this is a known problem in ANT V4. The impo ...

Unable to locate template or render function for Vue Draggable Next component

Looking to incorporate Vue Draggable Next into a Vue 3 example page but encountering some challenges. I've attempted to follow the instructions in the repository. However, I ran into issues when importing the Vue Draggable Next component and had to re ...

Animating an SVG in a circular motion starting from its central point with either CSS or XML

I've been grappling with the challenge of getting a part of my personal logo to rotate. My logo consists of "SB" and an asterisk, denoted as "st1," which is what I'm attempting to animate. Despite my attempts using XML and CSS, I've encounte ...

Issues with toggling the menu on Angular 14 using Bootstrap 4.6

I am struggling with implementing a menu on the header section of my Angular 14 homepage. The menu I added is not opening as expected. Even after trying various working menu samples from the internet, I couldn't get it to work in my project. Here are ...