Error encountered when using Type-Script with Vue.js and Data binding

Being relatively new to the realms of Java/TypeScript, I find myself struggling with a seemingly simple task that has consumed over three days of development time. Despite successful compiling and building processes without errors, I remain perplexed by the issue.

My project involves using vue.js3:

The problematic template looks like this:

<script setup lang="ts">

import type {CompanyPojo} from "@/rest/restapi-companies";
import {createNewCompany} from "@/rest/restapi-companies";

let companyPojo: CompanyPojo;

</script>


<template>

  <input id="cName" v-model="companyPojo.name" placeholder="Company Name"/>
  <label for="cName">Company Name</label>

  // <input id="cAddName" v-model="companyPojo.additionalName" placeholder="Company Additional Name"/>
  // <label for="cAddName">Company Additional Name</label>


  // <input id="cLegalForm" v-model="companyPojo.legalForm" placeholder="Company Legal Form"/>
  // <label for="cLegalForm">Company Legal Form</label>

  <button @click="createNewCompany(Object.assign(companyPojo))"> Add Company
  </button>


</template>

This is my TypeScript file snippet:

export type CompanyPojo = {
    id: number;
    name: string;
    legalForm: string;
    additionalName: string;
};

export type CompanyPojoResponse = {
    data: CompanyPojo[];
};

export async function createNewCompany(newCompany: CompanyPojo) {

    try {
        const {data, status} = await axios.post<CompanyPojoResponse>('http://localhost:9050/api/v1/company/create-new', newCompany,
            {
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: 'Basic XXXXXXXXXXXXXXXXXX',
                },
            },
        );

        console.log(JSON.stringify(data, null, 4));

        // ?? "response status is: 200"
        console.log('response status is: ', status);

        return data;
    } catch (error) {
        if (axios.isAxiosError(error)) {
            console.log('error message: ', error.message);
            console.log('error message: ', error);
            return error.message;
        } else {
            console.log('unexpected error: ', error);
            return 'An unexpected error occurred';
        }
    }


}

Upon importing the necessary files, I anticipated having access to all designated types during both development and runtime.

However, upon opening the New-Company View, I encountered an empty view accompanied by the following console error:

TypeError: (intermediate value)(...) is undefined setup http://localhost:9050/assets/CompanyNewView-215ff09f.js:1

Strangely enough, removing the following input elements resolves the issue:

 <input id="cName" v-model="companyPojo.name" placeholder="Company Name"/>
  <label for="cName">Company Name</label>

This situation is driving me crazy; how can I successfully bind and utilize these values? The reason behind their malfunction remains unknown to me...

Answer №1

In order for your data to be properly bound, it is important that it is reactive. Consider using the ref function to create your data property:

<script setup lang="ts">
import {ref} from 'vue'
import type {ProductPojo} from "@/rest/restapi-products";
import {createNewProduct} from "@/rest/restapi-products";

const productPojo = ref<ProductPojo>({});

</script>

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

Personalizing structural directives in Vue

Angular allows for the use of structural directives to manage how elements are displayed. Is it possible to define similar structural instructions in Vue? ...

Ways to identify and differentiate user clicks on various buttons

I have generated 3 different plan options from an array of objects retrieved from the backend. Depending on whether the plan is cheaper, the user's subscription, the corresponding button will display "downgrade", more expensive, the button will show ...

[Web Development]:

Having an issue with my HTML file where a JavaScript function named "CheckCaptcha" is not being executed when an image is clicked. I've been working on the code for hours, trying different tweaks and modifications, but it still can't seem to find ...

What could be the reason behind the disappearance of text from the previously highlighted button in my calculator's "button grid" when I change the highlighted button?

Currently, I am in the midst of creating a tip calculator with a grid consisting of various percentage buttons. My main objective is to change the font and background color when any tip button is selected. Nevertheless, an issue has surfaced - whenever I h ...

Is there a way to initiate multiple AJAX requests once a single request has been completed successfully?

I have created two functions and I want to call the get_name_from_id function when my first ajax function is successful. However, it is not working as expected. When I add an alert in the get_name_from_id function after the jsonString variable like alert ...

Error message: JavaScript is unable to save data to an array retrieved from Ajax, resulting in

I am facing an issue with retrieving continuous data from the database using AJAX and storing it in a JavaScript variable. Despite my efforts, I am unable to populate an array with the retrieved values as they always end up being undefined. Below are the s ...

Step-by-step guide for integrating npm into a Vue project

When attempting to run npm run server for my vue project, I encountered an issue where it would not work properly. https://i.sstatic.net/uaFKZ.jpg ...

jQuery still not running despite using .ready

I have been attempting to run some jQuery code on my HTML page. After doing some research, I learned that using .ready may be necessary to ensure the DOM is fully loaded before executing the script. Despite this, I am still having trouble getting the scrip ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

Uncovering the origin of a problematic included file

When using Sencha Touch, it is common to encounter issues related to missing files. In most cases, simply including the file resolves the issue. However, there are instances where the problem lies in a faulty include, requiring you to locate where the file ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

Having trouble with ReactJS updating the state in the correct format using moment?

In my ReactJS project, I am using a datepicker feature. However, I have encountered an issue where the state is not being updated with the selected date value after formatting it using moment.js. const [selectedDates, setSelectedDates] = useState([]) ...

What is the shebang used for in JavaScript?

In one article I came across, it was mentioned that by including #! /usr/bin/python in a file named testScript, running ./testScript from the command line would be the same as running /usr/bin/python testScript This concept seems plausible to me as most s ...

How can you efficiently access the 'app' object within a distinct route file?

When using Express 4, the default behavior is to load routes from a separate file like so: app.use('/', routes); This would load routes/index.js. I am working with a third-party library that directly interacts with the app object itself. What& ...

In Angular, when using multiple-selection mode in mat selection, the Error Value should always be in the form of

**Everything is working fine except for one error in the console. How can I remove this error? Can anyone please help me? Save, Edit, and searching are working perfectly fine. ** public campaignCategoryFormGroup$: FormGroup = this.fb.group({ // 'c ...

Merging RXJS observable outputs into a single result

In my database, I have two nodes set up: users: {user1: {uid: 'user1', name: "John"}, user2: {uid: 'user2', name: "Mario"}} homework: {user1: {homeworkAnswer: "Sample answer"}} Some users may or may not have homework assigned to them. ...

I encountered an issue while starting the VueJS build where an error message appeared stating: "Conflict: Multiple assets emit

After updating VueJS this morning, my app started encountering an issue. When I try to build it, an error message pops up stating: Error: Conflict: Multiple assets emit to the same filename img/default-contractor-logo.0346290f.svg Despite there being onl ...

I want to know how to showcase elements from a list one by one and cycle through them using a button with a nodejs server and Pug

As someone who is brand new to Web development, NodeJs servers, and Pug, this is my first time diving into any of these technologies. My goal is to create a dynamic box (in the form of a div) that changes its content based on a list from a JSON file. Initi ...

Experiencing difficulty importing Materialize CSS JS into React

Good day everyone, I've been facing challenges in implementing materialize css into my react-app, specifically with the JavaScript files. After trying various methods, I believe that I have made some progress using the following approach: In my &ap ...

Retrieve a specified child object within its parent object using a string identifier

I have a situation where I need to create a JavaScript function that can extract a child object from a parent object based on a specific string identifier. Here is an example of what I'm looking for: function findChild(parent, name) { return par ...