Encountering issues with accessing properties of undefined while chaining methods

When comparing lists using an extension method that calls a comparer, I encountered an error. Here is the code snippet:

type HasDiff<T> = (object: T, row: any) => boolean;

 export const isListEqualToRows = <T>(objects: T[], rows: any[], hasDiffFunction: HasDiff<T>): boolean => {
  if (objects.length !== rows.length)
    return true;

  return rows.every((row, index) => {
    const object = objects[index];
    
    if (row.isNew) {
      return false;
    }
    
    return !hasDiffFunction(object, row);
  });
};

The comparison is triggered by Angular's value changes in a ReactiveForm. Here is how it's implemented:

import { isListEqualToRows } from '@core/helpers';

formGroup.valueChanges.pipe(debounceTime(debounceValue)).subscribe((changes) => {
  this.areChangesDetected = !isListEqualToRows<Person>(this.items, changes, this.hasDiff);
});

My issue arises when dealing with a list within a list for one object. To handle this, I am attempting to call the isListEqualToRows() method again inside:

hasDiff(item: Person, row: any): boolean {
  return item.description !== row.description
    || !isListEqualToRows<Address>(item.addresses, row.addresses, this.hasDiffAddress);
}

hasDiffAddress(item: Address, row: any): boolean {
  return item.AddressId !== row.id
    || item.AddressStreet !== row.street;
}

However, running the second line of the hasDiff() method triggers an error:

Cannot read properties of undefined (reading 'hasDiffAddress')

How can I resolve this issue?

Answer №1

When you call hasDiff, make sure it is bound to the correct this object. If strict mode is enabled, calling hasDiff without proper binding will result in undefined being referenced as this. To fix this issue, instead of passing this.hasDiff to isListEqualToRows, use either this.hasDiff.bind(this) or

(item, row) => this.hasDiff(item, row)
.

Alternatively, you can add a thisArg argument to isListEqualToRows, where you pass this from the caller's scope and then invoke hasDiffFunction using

hasDiffFunction.call(thisArg, object, row)
instead of hasDiffFunction(object, row).

For more information on how the "this" keyword works, check out: How does the "this" keyword work?

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

"Commitment made ahead of time without allowing for the outcome to

I'm completely new to working with promises and I'm encountering some unexpected behavior in my code. The issue lies in the TaskRunner.SyncObjects function within Main.js, which should be waiting for the selectedCourses variable to be populated ...

Introduce regex in the middle

If I have a string in JavaScript like so: "test test hello test test" I understand how to replace 'hello' with 'byebye': replace("hello","byebye"); However, what is the most efficient method to add 'byebye' immediately afte ...

Is there a way to link a particular model table with a designated user table?

Hey everyone, I'm new to stack overflow and this is my first question. I hope it's clear enough for you all to understand. I'm currently working on a budget API using Node.js, Sequelize, Express, and PostgreSQL. The API allows users to add/ ...

Error message: Attempting to access the 'path' property of an undefined variable results in TypeError while utilizing cloudinary services

I am currently attempting to upload a file from React to an Express server, but I keep encountering this error TypeError: Cannot read property 'path' of undefined The method I am using involves React for transferring/uploading the file to the ...

Conceal any ng-repeat elements that do not contain corresponding grandchildren within two levels of nested ng-repeats

Apologies for the enigmatic title, but the issue at hand is quite cryptic ¯\_(ツ)_/¯ I'm dealing with a complex problem involving 3 nested ng-repeats to display Google Analytics' account structure. Within this structure are multiple acco ...

The parameter is causing the Aggregate Function to malfunction

When fetching MongoDB data, I encountered an issue. Using the JavaScript parameter to retrieve data from MongoDB resulted in a null return, but manually typing it brought all the data without any problems. That part is working fine. const data = await Numb ...

Enhance the Component Props definition of TypeScript 2.5.2 by creating a separate definition file for it

I recently downloaded a NPM package known as react-bootstrap-table along with its type definitions. Here is the link to react-bootstrap-table on NPM And here is the link to the type definitions However, I encountered an issue where the types are outdate ...

What is the method for enabling imports from .ts files without file extensions?

While trying to open a Svelte project with TypeScript, I encountered an issue where all imports from .ts files were showing "Cannot resolve symbol" errors. https://i.stack.imgur.com/FCVxX.png The errors disappear when the .ts extension is added to the im ...

Tips on how to conditionally render a button based on the presence of a link from a separate file in React

I've been working on my personal portfolio site using React and Tailwind. One challenge I'm facing is how to display the "GitHub" button for each project card only when a GitHub link is provided in my data.js file. Currently, I'm utilizing ...

Angular often uses the JavaScript pattern for development

After completing an AngularJS tutorial on http://www.tutorialspoint.com/angularjs/angularjs_services.htm, I found myself puzzled by the method used in the CalcService service. It seemed unclear whether Angular was using revealing prototype or a different ...

Launching a React build using Docker on Apache or AWS

I am a beginner to the world of docker and react. My goal is to successfully deploy a production build on AWS. Here are the steps I have taken so far: Created a dockerfile. Built and ran it on the server. npm run and npm run build commands are functionin ...

Organizing entries based on the quantity of attached documents

I am currently working with mongodb and mongoose. I have a situation where users can create ratings and reviews for products. I want to retrieve the review of the product that has received the highest number of votes. Is this achievable in mongo? The data ...

Transfer only designated attributes to object (TS/JS)

Is it feasible to create a custom copy function similar to Object.assign(...) that will only copy specific properties to the target? The code snippet I have is as follows: class A { foo?: string; constructor(p: any) { Object.assign(this, p ...

`Only firing event listener once`

I have created a JS module where I am adding a click event to all links that match a specific selector. Here is an example of how it's done: var Lightbox = (function () { var showLightbox = function () { // this does stuff }; var init = fu ...

What is the best way to integrate ag-grid with Observable in Angular 2?

After conducting extensive research on the Internet, I am still struggling to connect the pieces. My angular2 application utilizes an Observable data source from HTTP and I am attempting to integrate ag-grid. However, all I see is a loading screen instead ...

Loading Objects with Material Textures Ahead in Three.js

I am faced with the challenge of preloading multiple obj+mtl files using Three.js, each with distinct file paths, and I need to trigger another function once all the objects have finished loading. Initially, I attempted to use a boolean variable that woul ...

Is there a way to determine if an element has been scrolled past?

I am currently working on a script to detect when a specific element comes into view while scrolling. const targetElement = document.getElementById('sidebar'); window.addEventListener('scroll', () => { if (window.scrollY > tar ...

What could be causing the TypeScript exhaustive switch check to malfunction?

How come the default case in the switch statement below does not result in an exhaustive check where 'item' is correctly identified as of type 'never'? enum Type { First, Second } interface ObjectWithType { type: Type; } c ...

Troubleshooting: Why is my AngularJS Controller not functioning properly

I attempted to run a basic Angular example utilizing a controller, but it does not appear to be functioning correctly. Below is the HTML code: <!DOCTYPE html> <html ng-app = "app"> <head> <title></title> ...

What is the process for displaying a document file in an iframe that is returned from a link's action?

I have a main page called index.cshtml. This page displays a list of document files along with an iframe next to it. My goal is to load the selected document file into the iframe when I click on any item in the list. However, currently, when I click on a d ...