Received Object instead of the anticipated Type T in the Vue-Prop for a custom Object

Description

Hello everyone,

I am excited to showcase my Vue-components on bit.dev.

Here is a Vue-component snippet:

<template>
    ...
</template>

<script>

import CustomItem from "../../../../objects/CustomItem";

export default {
    name: "Test",
    props: {
        item: {
            type: CustomItem,
        },
    },
};
</script>

This component specifically requires the prop to be a certain object.

This object is known as CustomObject

export default class CustomItem {
    constructor ({id, name}) {
        this.id = id;
        this.name = name;
    }

   // provide cool functions here
}

This setup works perfectly in my own project. However, when I try to include it like this:

<template>
    <div v-if="!$wait.is('item.loading')">
        <MyComponent :item="item"/>
    </div>
</template>

<script>
import MyComponent from '@bit/myproject.my-component'
import CustomItem from '@bit/myproject.custom-item';

export default {
    name: 'Home',
    components: {MyComponent},
    data () {
        return {
            item: {}
        };
    },
    beforeRouteEnter (to, _from, next) {
        const promises = [
            axios.get (`/api/item/1`)
        ];

        next (vm => {
            vm.$wait.start ('item.loading');
            axios.all (promises)
            .then (([itemRes]) => {
                vm.item = new CustomItem(itemRes.data.data);
            }).finally(()=>{
                vm.$wait.end ('item.loading');
            });
        });
    },
};
</script>

In this scenario, I encounter the following error:

[Vue warn]: Invalid prop: type check failed for prop "item". Expected T, got Object 

found in

---> <MyComponent> at resources/js/components/Items/MyComponent.vue

What could be causing this issue?

Edit

Upon closer inspection, I realized that the component @bit/myproject.my-component provided by bit.dev offers a packed and minified version of my component. In this minimized version, the prop structure appears like this:

props:{item:{type:function t(e){var n=e.id,r=e.name})...

It seems like this might be the root cause of the problem.

Answer №1

It appears that in your project, you have two classes named CustomItem:

  • The first one is imported relatively:
import CustomItem from "../../../../objects/CustomItem";
  • And the second one is imported as an external package:
import CustomItem from '@bit/myproject.custom-item';

I suggest trying to consolidate your imports into one form:

import CustomItem from '@bit/myproject.custom-item';

In the world of JavaScript, things can get complicated, and just changing your import statements may not solve the issue entirely. Sometimes, even specifying CustomItem in a particular way doesn't guarantee there won't be multiple occurrences of it in your production codebase. To tackle this problem, I recommend implementing 'duck-typing' in a custom props validator if verifying the type of the prop is crucial. Since using JS instanceof or checking

item.prototype.name === 'CustomItem'
may not be reliable due to code minimization altering class names, duck-typing seems like the most logical solution for your situation.

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

Deciphering the JavaScript code excerpt

This information was sourced from (function ($, undefined) { // more code ... $.getJSON("https://api.github.com/orgs/twitter/members?callback=?", function (result) { var members = result.data; $(function () { $("#num- ...

What is the best way to retrieve specific feature properties in Open Layers 3 on-the-fly?

Within my map, I have two types: Point and Polygon, each with unique properties such as id, door number, and name. I have generated a list of features as follows: var features = new ol.format.GeoJSON().readFeatures(geojsonObject, { featureProjection: & ...

Ways to create a group label to modify various textboxes when a click event occurs

Is it possible to change multiple textboxes with corresponding labels after a click event? Issue: The current output only displays the value of the last textbox. $(function () { $('a.edit').on('click', function (e) { e.pre ...

JavaScript function that loads different configuration files based on the URL

My mobile website currently fetches a config.json file using the provided JavaScript code: $.ajax({ type:'GET', url: '/config.json', contentType: 'plain/text; charset=UTF-8', dataType: 'js ...

When the parent component in React JS rerenders, the props are not automatically passed down to the child

I have come across similar questions in the past, but I have not found any answers that directly address the issue I am facing in my scenario. In my case, there is a parent component that passes a property to a child component's state. Depending on t ...

If the Request does not recognize the OAuth key, generate a fresh new key

I am working with a React Native Frontend and an Express.js backend. The backend makes calls to a 3rd party API, which requires providing an OAuth key for the user that expires every 2 hours. Occasionally, when calling the API, I receive a 400 error indi ...

The Highchart formatter function is being called twice on each occasion

My high chart has a formatter function that seems to be running twice. formatter: function() { console.log("starting formatter execution"); return this.value; } Check out the Fiddle for more details! ...

Is toastr functionality affected by bootstrap 5 updates?

I have recently updated my web app to use the latest version of Bootstrap 5 along with the toastr library. However, I have encountered issues with toastr options not functioning properly after the upgrade. Despite setting the values for toastr.options.time ...

What is the best way to conceal a dynamically-loaded element on a webpage?

I wrote a script that utilizes AJAX to fetch data from a PHP file named names.php. Later in the script, I used jQuery's $(document.ready(function(){}); to attempt hiding a div when the DOM is loaded. Strangely, the $("div").hide() function isn' ...

Is Ajax capable of producing multiple outputs at once?

I am looking to retrieve data from a product.json file that contains two objects: (1) object for CCTV camera products (2) object for Laptop products. When a specific button is clicked, I want to access the data for LAPTOP products and the same for CCTV. ...

If the condition has a class name of condition, then display

Having performance issues due to slow data rendering with each tab using a partial view. The code snippet for each tab is as follows: <div class="tab-content" ng-controller="MyController"> <div id="tab-1" class="tab-pane fade active in " ng-i ...

Camera Capacitor designed to eliminate popup notifications

I am utilizing Angular along with the camera plugin in Capacitor to locally save images on both desktop and tablets. I aim to utilize the CameraSource to directly access the camera or open the gallery for files without displaying a prompt. This is how my ...

Comparing various indexes within an array using JavaScript array functions

I am currently facing a challenge with comparing non-consecutive indexes in an array. For instance, how can I compare index 0 with all the other indexes until reaching index 3 in a given array like this: const arr = ["Juan", "Maria", & ...

Highlighting syntax on the server side

I have some code blocks that I want to emphasize. Currently, I am using prismjs for this purpose. However, when I try to highlight several code blocks, the page takes more than 5 seconds to load on my somewhat slow PC. Interestingly, if I remove the prism ...

jQuery's callback handling often reverses the statement I just made

My current project involves using AJAX with jQuery to send a get request. Once the request is successful, I insert the response into a specific div: $.get("content.php", function(result) { $('#content').html(result); The content I'm fetc ...

Update persistent angular data using grunt automation

Is there a way to dynamically set the remote URL based on my environment in AngularJS? For example: app.constant('fooConst', { urlBase: window.location.origin + '/bar/', urlBaseWebservice: window.location.origin + '/foo/&apos ...

The click event listener declared with v-on inside a Vue Component fails to trigger

I am currently working on a Vue instance for a sidebar within my application that displays a list of menu items. In order to achieve this, I have created a local component with the following template structure: template:'<div><li class="cust ...

Tips for accessing image data generated by the Bootstrap File Input plugin

I have a div that utilizes the Bootstrap File Input plugin to select, show, change, and cancel images. The image data is generated dynamically by the plugin. <div class="fileinput fileinput-new" data-provides="fileinput"> <div class="fileinpu ...

Guide on Crafting an Interactive Breadcrumbs Component

How can I implement product category breadcrumbs on the product page? These breadcrumbs will represent the parent category of the product. I am utilizing Next.js and Strapi for this project. For example, here is a screenshot showing how it should look: ...

Beginner Polymer Kit including Node, Express, and Puppeteer for a seamless development experience

Hey there, I'm completely new to this so any guidance would be greatly appreciated. I've recently figured out how to use Node and Express to serve a Polymer Starter Kit (PSK) website from the Polymer build directory by creating a server.js file ...