Vuejs class-based components using typescript face limitations when it comes to updating data from an external API

Currently, I am utilizing VueJS alongside Typescript and class-based components. In my code, I encountered a warning that states:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "upcomingexams"

Within UpcomingExams.vue file:

<template>
    <div class="card">
        <ul class="examlist">
            <li v-for="exam in upcomingexams" :key="exam.examId">
                {{ exam.examId }} on {{ exam.start }}
            </li>
        </ul>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";

export interface Exam {
  examId: string;
  questions: string[];
  correctAnswers: string[];
  start: Date;
  end: Date;
  course: string;
  schools: string[];
}

@Component
export default class UpcomingExams extends Vue {
@Prop() upcomingexams!: Exam[];

mounted() {
    console.log("UpcomingExams component mounted");
    this.getExamsAfterToday();
}

getExamsAfterToday() {
    var date = new Date();
    fetch("http://localhost:3000/api/queries/Q1?todayDatetime=" + date.toJSON())
    .then(response => response.json() as Promise<Exam[]>)
    .then(data => (this.upcomingexams = data));
}
}
</script>

I attempted to switch the Prop to data by removing the @Prop() decorator. Unfortunately, this resulted in the following error message:

Property or method "upcomingExams" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Despite initializing it with the bang, I am unsure of what might be causing this issue.

Answer №1

It took me a while to figure it out, but eventually I realized that bang initialization was causing an issue with Vue. Moving the declaration of upcomingexams to

upcomingexams: Exam[] = []; solved the problem.

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

Encountered an issue with valid types while executing the following build

Encountering an error when attempting to run the next build process. https://i.stack.imgur.com/qM3Nm.png Tried various solutions including updating to ES6, switching the module to commonJs, downgrading webpack to version 4 with no success. The only worka ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Tips for sending a value to a container component

Within my task management application, I have implemented two selectors: export const selectFilter = (state: RootState) => state.visibilityFilter export const selectVisibleTodos = createSelector( [selectTodos, selectFilter], (todos: Todo[], filter : ...

Is it possible to use a single type predicate for multiple variables in order to achieve type inference?

Is there a way to optimize the repeated calls in this code snippet by applying a map to a type predicate so that TSC can still recognize A and B as iterables (which Sets are)? if(isSet(A) && isSet(B)) { ...

What is the best way to remove an element from an array and add a new one?

Here is the array that I am working with: [ { "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2" ...

Tips for expanding a Vue 3 component

When I try to use the component directly from the element-plus library, the import works perfectly. My goal is to extend a component from the element-plus library, which utilizes the composition api from Vue 3, and add additional properties and methods to ...

WebStorm is failing to identify globally scoped external libraries

I'm currently working on a project using AngularJS (1.6.5) in WebStorm. The issue I'm encountering is that WebStorm isn't recognizing the global variables that AngularJS defines. I've made sure to install AngularJS and the correct @type ...

Warning: When using Vuex and Mocha together, committing mutations in tests may result in the warning 'Avoid mutating Vuex store state'

Greetings, thank you for taking the time to read this. I am currently facing an issue while trying to run automated tests on my Vuex-supported application. The problem arises when committing a mutation in a Mocha test file, triggering a warning from Vuex ...

Vue.js and axios seem to be failing to produce a response

Is it possible to access the OMDB API using Vue.js and Axios? I'm facing an issue where, when I pass a query from an input field to axios within the findId method, nothing is being console logged. There are no errors or responses returned. What could ...

Generate a fresh array using the data from the existing array object

I have nested objects within arrays that I need to manipulate. { "page": [ { "num": "1", "comp": [ { "foo": "bar", "bar": "foo", ...

Combine objects by selecting attributes from multiple objects

declare type A = {type: 'TypeA', attr1: string} declare type B = {type: 'TypeB', attr2: string} declare type U = A | B When I use type X = Pick<U, 'type'>, I get: { type: 'TypeA' | 'TypeB' } But I a ...

Creating a Vuetify table with dynamic column values dependent on API data

https://i.sstatic.net/KlQ1x.png I have a simple function that displays the attribute name based on the ID. displayAttributeNameBasedOnId(id) { axios.defaults.headers['Content-Type'] = 'application/json' let data = { $r ...

Utilize Charts.js to transform negative values into graphical representations

I am struggling with transforming the expense data into a positive number in my bar chart. The data consists of both income and expenses, and I want to display them as positive numbers for easier comparison. I attempted using Math.abs(this.barData[1]) in n ...

Expanding the value in Vue2 using a method

I'm seeking a simple solution here. I have a single component structured like this: export default defineComponent({ name: "Home", setup() { const { pages, loading, error } = useGetPages(); return { pages, loading, error }; }, ...

ag grid - issue with icons not appearing correctly

<script> import {AgGridVue} from "ag-grid-vue"; import 'ag-grid-enterprise'; import 'ag-grid-community/dist/styles/ag-grid.scss'; import "ag-grid-community/dist/styles/ag-grid.css"; import "ag-grid-community/dist/styles/ag-theme-a ...

Update the second dropdown list based on the selection made in the first dropdown list in Vue.js

My goal is to dynamically change the options in the second select list based on the value selected in the first one. I initially achieved this by creating two separate Vue instances for each select, but I wanted a more streamlined approach for a cleaner ap ...

Transforming ReactJS files into TypeScript (.tsx) files

An error in TypeScript occurred while trying to convert a React project to TypeScript. Error Message: TypeScript error in /src/App.tsx(34,44): No overload matches this call. Overload 1 of 2, '(props: RouteProps | Readonly<RouteProps>): Route&l ...

Cluster multiple data types separately using the Google Maps JavaScript API v3

I am looking to implement MarkerClusterer with multiple markers of various types and cluster them separately based on their type. Specifically, I want to cluster markers of type X only with other markers of type X, and markers of type Y with other markers ...

What are the steps to incorporating the pick function in TypeScript?

The TypeScript documentation mentions a pick function that is declared but not implemented. In an attempt to create a simplified version, I wrote the following: function pick<T, K extends keyof T>(obj: T, key: K): Pick<T, K> { return { [key]: ...

I'm interested in developing a feature that monitors a specific attribute and triggers a function once that attribute hits the value of 100

I am working on a function that will refresh the view once the percentage changes reaches 100: The value is stored in this variable: this.uploadPercent = task.percentageChanges(); This is the function I plan to implement : refreshView(){ Once this.uplo ...