Chart.js is encountering an issue where it cannot access the property 'apply' as it is undefined

When attempting to update the Chart using Chart.js, I encountered an error upon calling the push method. The specific error message received is as follows:

ERROR TypeError: Cannot read property 'apply' of undefined
    at Object.value (Chart.js:3574)
    at ErrorComponent.updateChart (error.component.ts:132)
    at ErrorComponent.set timelineChart [as timelineChart] (error.component.ts:38)
    at ErrorComponent_Query (error.component.ts:33)
    at executeViewQueryFn (core.js:13733)
    at refreshView (core.js:12059)
    at refreshComponent (core.js:13445)
    at refreshChildComponents (core.js:11716)
    at refreshView (core.js:12051)
    at refreshEmbeddedViews (core.js:13391)

The approach I am currently taking involves creating the chart once the Angular component is initialized and updating it with new data from HTTP requests. Here is the code snippet I have implemented so far:

private static formatData(errorOccurrences: ErrorOccurrence[]): {x:Date,y:number}[] {
    if (!Array.isArray(errorOccurrences)) {
      console.warn('ErrorOccurrences is not an array');
      return;
    }

    const occurrencesByHour = {};
    for (const errorOccurrence of errorOccurrences) {
      const occurrenceTimeStampRounded = ErrorComponent.roundDateBy3Hours(new Date(errorOccurrence.timeStamp));
      if (occurrencesByHour.hasOwnProperty(occurrenceTimeStampRounded)) {
        ++occurrencesByHour[ErrorComponent.roundDateBy3Hours(new Date(errorOccurrence.timeStamp))];
      } else {
        occurrencesByHour[ErrorComponent.roundDateBy3Hours(new Date(errorOccurrence.timeStamp))] = 1;
      }
    }

    const data: {x:Date,y:number}[] = [];
    for (const key of Object.keys(occurrencesByHour).map(q => parseInt(q))) {
      data.push({x: new Date(key), y: occurrencesByHour[key]})
    }
    console.log(data);
    return data;
  }

  private updateChart(): void {
    if (!this._chart) {
      return;
    }

    const data = ErrorComponent.formatData((this.reportedError as StandardReportedError).standardErrorOccurrences);
    for (const dataLine of data) {
      console.log(dataLine);
      this._chart.data.datasets[0].data.push(dataLine);
    }

    this._chart.update();
    this.isLoadingOccurrences = false;
  }

  private createChart(element: ElementRef<HTMLCanvasElement>) {
    if (this._chart || !element) {
      return;
    }

    const occurrencesByHour = []
    let timeStamp = ErrorComponent.roundDateBy3Hours(new Date());
    for (let i = 0; i < 24;i++) {
      occurrencesByHour.push(new Date(timeStamp - (10800000 * i)));
    }

    this._chart = new Chart(element.nativeElement, {
      type: 'line',
      data: {
        labels: occurrencesByHour,
        datasets: [{
          data: {}
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        fill: 'start',
        legend: {
          display: false
        },
        scales: {
          xAxes: [{
            type: 'time',
            distribution: 'series'
          }],
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });
  }

This marks my debut question on Stack Overflow, so please forgive any ambiguities in my query.

Answer №1

A similar issue troubled me in the past. Make sure to validate the length of the object being passed to the chart before displaying it.

{ data.length > 0 && <Line options={options} data={data}/> }

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

Ways to help a child notice when a parent's variable changes

Looking for help with passing data to a child component? Check out this Plunker: http://plnkr.co/edit/G1EgZ6kQh9rMk3MMtRwA?p=preview @Component({ selector: 'my-app', template: ` <input #x /> <br /> <child [value] ...

Unable to connect dynamic information in Angular 8 component

Error encountered during dynamic component loading DynamicBuilderComponent.ngfactory.js:198 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: The expression has changed after it was checked. Previous value: 'ng-pristine: true'. Current ...

Tips on toggling the visibility of an element in Angular 4

This is my unique html element: <ng-container> <span *ngIf="row.messageText && row.messageText.length >= 30 && expanded">{{row.messageText.substr(0, 25)}} <span>more</span> </span> ...

How should the Facebook avatar be displayed using AngularFire in a correct manner?

I am working on an app where I want to display the avatar of the logged-in Facebook user, but I'm struggling to find a clean solution. To show the user's avatar, you need to have their user_id and accessToken. While user_id can be obtained using ...

Angular <select><option> tags are missing from the browser display, although they are present in the source HTML code

After incorporating a dropdown list into the FormGroup, it seems to be missing from the browser display. Upon inspecting the page's HTML source on Chrome, I noticed that the <select><option></option></select> element is present ...

Navigating through a mergeMap observable with an undefined value

In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken() method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning. I need help with handling th ...

Guide to testing error throwing in error events with Jest

I am having an issue with a particular learning case. The code snippet below is what I am dealing with and I aim to test error throwing: export const someFunction = async () => { //... const fileReadStream = createReadStream(absoluteFilePath) .on(&a ...

Differences between Pipe and Tap when working with ngxsWhen working with

While experimenting with pipe and subscribe methods, I encountered an issue. When using pipe with tap, nothing gets logged in the console. However, when I switch to using subscribe, it works perfectly. Can you help me figure out what I'm doing wrong? ...

Angular has the ability to round numbers to the nearest integer using a pipe

How do we round a number to the nearest dollar or integer? For example, rounding 2729999.61 would result in 2730000. Is there a method in Angular template that can achieve this using the number pipe? Such as using | number or | number : '1.2-2' ...

How can you efficiently refresh cached data for multiple related queries after a single mutation in react-query?

Within my codebase, I have a few queries that need to be addressed: Retrieve all articles useInfiniteQuery( ['articles', { pageSize: props.pageSize }], queryFn ); Fetch articles within a specific category useInfiniteQuery( [&ap ...

Using injected services within static methods may seem tricky at first, but once you

I am exploring the integration of angularjs and typescript in my project. Currently, I am working on creating an Orm factory using typescript but have encountered some challenges. The structure of my factory class is as follows: class OrmModel implements ...

Incorporating two components and nesting one within the other, similar to the way angular-material seamlessly integrates its components

I recently discovered the angular-material module and I'm a bit perplexed about how it allows multiple components to be used inside one another in the same place. Take a look at the example below: <mat-drawer-container class="example-container"> ...

Is there a way for me to directly download the PDF from the API using Angular?

I'm trying to download a PDF from an API using Angular. Here's the service I've created to make the API call: getPDF(id:any) { return this.http.get( `url?=${id}`, { responseType: 'blob' as 'json', obs ...

access denied on image links

While developing a web app with Angular5, I encountered an issue regarding retrieving image URLs from the 4chan API. Each post in my database contains an image URL, however, when I try to access it through my app, I receive a 403 forbidden error in the con ...

Jest encountered a syntax error due to an unexpected token <

When attempting to run a test using jest with a typescript preprocessor, I encountered the following error: var component = react_test_renderer_1["default"].create(<jumbotron_1["default"] />); ...

Ways to utilize a previous acquisition

After purchasing a consumable product, I forgot to consume it during my release. I made changes to my code so now the unpurchased products are not available for purchase anymore. When I attempted to use restorePurchases to consume the products that were n ...

The user interface is not being refreshed in the select box after removing control from the reactive form

Within my project, I am utilizing "@angular/cli": "1.2.6", "@angular/core": "^4.0.0" Objective My goal is to create a dynamic form for a product that includes feature inputs. When the user clicks the "add feature" button, a new feature column with a sel ...

Changing the default font size has no effect on ChartJS

I'm trying to customize the font size for a chart by changing the default value from 40px to 14px. However, when I set Chart.defaults.global.defaultFontSize to 14, the changes don't seem to take effect. Below is the code snippet for reference. An ...

Is NX capable of speeding up the performance of ng serve?

Just starting out with NX... NX is designed to enhance the Angular CLI by leveraging computation caching for faster performance. When using nx build, builds are completed almost instantly thanks to caching. However, I'm curious if nx serve also uti ...

What is the best way to retrieve the Base64 string from a FileReader in NextJs using typescript?

My goal is to extract a string from an object I am receiving in the response. const convertFileToBase64 = (file: File): Promise<string> => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.r ...