The Ionic framework is throwing an error message: "Unable to determine the length of undefined property

I am stuck with an error and need some help. I have declared variables like this:

jdetails: Array<any>;
cards: Array<any>;

This is the method I am using:

ionViewDidLoad() {
    console.log('ionViewDidLoad FeedsPage');
    //for new card
    this.addnewcard();
    console.log(this.cards);
  }
addnewcard() {
    this.jobdetail.getJobDetails().then((data) => {
      //console.log(data);
      this.jdetails = data;
    });
    for (let val of this.jdetails) {
      this.cards.push(val);
    }
  }

Whenever I press a button, the "voteUp" method gets executed.

voteUp() {
    let removedcard = this.cards.pop();
    this.addnewcard();
  }

Unfortunately, I am encountering a type error.

ERROR TypeError: Cannot read property ‘length’ of undefined at FeedsPage.webpackJsonp.260.FeedsPage.addnewcard (feeds.ts:171) at FeedsPage.webpackJsonp.260.FeedsPage.ionViewDidLoad (feeds.ts:63) at ViewController._lifecycle (view-controller.js:486) at ViewController._didLoad (view-controller.js:369) at NavControllerBase._didLoad (nav-controller-base.js:768) at t.invoke (polyfills.js:3) at Object.onInvoke (core.js:4749) at t.invoke (polyfills.js:3) at r.run (polyfills.js:3) at NgZone.run (core.js:4566)

Answer №1

Note: encountering the error message

Cannot read property ‘length’ of undefined
typically happens when there is a direct reference to arr.length, which doesn't seem to be present in your provided example. I do see instances where it appears that this.cards is undefined.

It seems like you are iterating over the this.jdetails member before it has been properly set (the .then indicates asynchronous execution):

this.jobdetail.getJobDetails().then((data) => {
  //console.log(data);
  this.jdetails = data;
});
for (let val of this.jdetails) {
  this.cards.push(val);
}

To address this issue, ensure that the data processing occurs only after it has been fetched by moving the loop inside the .then function.

this.jobdetail.getJobDetails().then((data) => {
  //console.log(data);
  this.jdetails = data;

  for (let val of this.jdetails) {
    this.cards.push(val);
  }
});

While I'm unable to view all of your code since a self-contained example was not provided, it's important to note that when using push or pop, there needs to be an initialized array beforehand. You can initialize it either inline or within your constructor:

cards: any[] = [];

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

Navigating to the detail page following a POST request in RTK query: A step-by-step guide

In my React RTK-query form, I am facing an issue where after a POST request is made, the form should navigate to the next step. However, in order to do that, I need to obtain the id of the newly created record. The backend auto-increments the id and does n ...

Preparing an Angular 2 application for deployment on a live IIS server

After following the Angular 2 tutorial successfully and getting everything to work as expected, I realized that it doesn't cover packaging for production distribution. Is there a standard method for creating a clean distribution package without includ ...

Setting a value in the selectpicker of rsuitejs involves assigning a specific value to the

const _DATA = [{ code: 'code1', name: 'Jagger' },{ code: 'code2', name: 'Tigger' },{ code: 'code3', name: 'Lion' }] <SelectPicker data={_DATA.map(x => {return {label: x.n ...

Encountering issues while trying to update npm in a Angular 6 project

Attempting to upgrade npm from version 6.1.0 to 6.4.0 using the command line interface: npm install -g npm Unfortunately, encountered an error during the update process. npm ERR! path /usr/local/lib/node_modules/npm/node_modules/ansi-regex npm ERR! co ...

Is there a way to display only the year in the Angular ngx boostap 2.0.5 datepicker?

https://i.sstatic.net/UYqFi.png https://i.sstatic.net/0EHIx.png My goal is to display only the year in the datepicker, but when I select a year, the month appears afterwards. How can I adjust this? ...

What is the process for modifying event (hover & click) on a legend item within highcharts?

When hovering over chart points, you can see the point value in the center of the pie chart. Similarly, when you stop hovering over a chart point, you can see the total value displayed. This behavior also applies when hovering over a legend item. const cha ...

Angular binding data property for displaying Twitter timelines using ngx-twitter-timeline

I've been struggling to set the data property of ngx-twitter-timeline programmatically. Below is the code snippet I am working with: <ngx-twitter-timeline [data]="{sourceType: 'url', url: 'https://twitter.c ...

What is the correct way to define types for higher-order class components in TypeScript?

I have developed a utility function that currently has an unused options parameter, and it returns a higher-order component wrapping function. How can I effectively define types on the component so that users of the wrapped component can visualize the typ ...

TypeScript - ensuring strict typing for particular object keys

In my current project, I am using typescript and working on defining an interface that has the following structure: interface SelectProps<T> { options: T[]; labelKey: keyof T; valueKey: keyof T; } The type T in this interface can vary i ...

Unable to show buttons when hovering over them

My goal is to have a set of buttons displayed when the user hovers over a specific button (Settings). I managed to achieve this by hiding the Settings button when the user hovers over the current div element and showing the other buttons instead. <div ...

Utilizing Ionic to import and parse an Excel file for data processing

I need assistance in uploading an Excel file and reading it using Ionic-Angular. I tried the following code, but it only seems to work for browsers and not for the Ionic app on Android. Can someone please help me with this issue? I am trying to read the E ...

Creating custom disabled button styles using TailwindUI in a NextJS application

I had a NextJS application that utilized Atomic CSS and featured a button which becomes disabled if a form is left unfilled: <Button className="primary" onClick={handleCreateCommunity} disabled={!phone || !communi ...

Angular 4 issue: Changing the value in the HTML 5 slider does not trigger the onchange/input event

Below is the html 5 slider along with a button <button type="button" class="btn btn-default zhaw-ict-icon zhaw-icon-hinzufugen zoom-in" (click)="zoomIn()"></button> <input class="btn zoom" type="range" min="1" max="300" [value]="currentZoom ...

Is there an issue with loading a local image? Could it be related to Angular or Chrome

Currently, I am working on a webpage that is designed to showcase a collection of images. The API I am using returns a list of objects, each containing an imgUri property which holds the absolute path to the corresponding image stored in a shared folder. ...

Encountered an issue while trying to load webpage on iOS device. NSURLErrorDomain error -999 was returned while deploying Ionic app

My Ionic 4 app successfully deploys to Android, but I encountered issues deploying to iOS in Xcode. After resolving the problem, it has started failing again with the following error message: 2019-09-09 20:28:09.836175-0400 [962:15259] Apache Cordova na ...

Incorporate form controls within a table and implement merging capabilities in Angular 9

Can I insert form controls within table cells, and implement a merge feature for these table cells? For instance, if I merge two cells, will one of the controls extend to fill the vacant space? I am looking to create a basic spreadsheet with cell mergi ...

Positioning gallery images in Angular Modal Gallery

I'm currently working on implementing an image modal, but I've run into several issues. My goal is to have the first image fill the entire large box (class drop), with the rest displayed below it, as illustrated in the image. I've experime ...

Leverage the power of InfiniteSWR in your project by integrating it seamlessly with

If you're looking for a comprehensive example of how to integrate useSWR hooks with axios and typescript, check out the official repository here. import useSWR, { SWRConfiguration, SWRResponse } from 'swr' import axios, { AxiosRequestConfig, ...

Is it recommended to ensure all of my components are nested within the root App component?

As I delve into learning Angular 4 with angular-cli for creating a web front end, I can't help but wonder about the structure of my components. In following the Heroes tutorial and applying it to my own data models, I noticed that all my components, ...

Updating the selected state of an Angular 2 material mat-chip

Attempting to update the selected property of a chip named "chip" results in an ExpressionChangedAfterItHasBeenCheckedError when changing the binding property. HTML <mat-chip-list> <mat-chip *ngFor="let w of weekDays" [selectable]="tru ...