What could be causing the issue with the variable appearing as undefined in

My class has a property:

public requestLoadPersonal: Personal[] = [];

As well as a method:

private filterByGender(selectedValue: any): void {
    console.log(this.requestLoadPersonal);
    this.requestLoadPersonal = this.requestLoadPersonal.filter(
      (p: Personal) => {
        return selectedValue ? p.gender == selectedValue : true;
      }
    );
  }

In the constructor of my class, I initialize:

 public filterFn = {
    name: this.filterByGender
 }

I am puzzled by why when I call the function this.filterByGender from the object filterFn using its key, I receive an undefined message. The variable this.requestLoadPersonal seems to be unavailable inside:

console.log(this.requestLoadPersonal);
?

The method is called like this:

 this.filterFn['name']({...});

I have attempted to bind the variable:

 this.filterFn['name']({...}).bind(this.requestLoadPersonal);

Answer №1

When setting up your constructor, ensure you bind the function to this in this manner:

constructor() { this.filterFn = { name: this.filterByName.bind(this) }; }

If you simply use {name: this.filterByName}, the this context is lost, meaning that filterByName will have the this context of a different instance.

It might be wise to simplify and streamline your approach for better clarity and fewer chances of errors in the code.

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

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

JavaScript Recursive Function for Generating FancyTree JSON Structure

I'm currently building an array of JSON objects for FancyTree (https://github.com/mar10/fancytree/wiki/TutorialLoadData). My JSON source is from the Jira REST service, and its structure can vary widely. Therefore, the code to construct the array of JS ...

How can we transfer or exclude all boolean properties from one class to another or a "type"?

Within my Nestjs application, there is an entity class structured like this: @ObjectType() export class Companies { @Field(() => Int) @PrimaryGeneratedColumn({ type: 'int', name: 'id' }) public id: number; @Field() @Column ...

"Implementing a Callback Function when Jquery Countdown Reaches

Implementing this plugin will result in a live countdown displayed on the webpage. I recently reviewed the on.finish callback documentation found on the Official website. The main objective is to hide the span#limit once the timer completes its countdown ...

React- The Autocomplete/Textfield component is not displaying properly because it has exceeded the maximum update depth limit

My autocomplete field is not displaying on the page even though I wrapped it with react-hook-form for form control. When I check the console, I see this error: index.js:1 Warning: Maximum update depth exceeded. This can happen when a component calls setSt ...

Check the validity of a password using Angular's reactive forms

For my password validation using ng Reactive Forms, I have a basic html input field for the password and warning paragraphs outlining the password requirements. <div class="field"> <label class="label">Password</label ...

Search for a DIV element within iMacro on a consistent basis

I recently started using iMacro and encountered an issue while recording a script that involved clicking on a pop-up when it appeared on the screen. The problem arose because the pop-up only appears when a new event is posted. Therefore, when I initially c ...

Starting over fresh after clearing the interval

Visit the test site Is there a way to reset the animation back to the beginning once it reaches the last image? I've attempted the code below, but it doesn't seem to bring it back to the first image. $(document).ready(function () { window. ...

There seems to be an issue with the $scope variable not being properly updated within the function in

<button class="button button-primary" ng-click="updateSchedule(controlCenter.selected)"> Update Schedule </button> Calling the updateSchedule function from the button $scope.data = []; $scope.updateSchedule = function(selectedData) ...

Creating a unique field button in AngularJS that is dynamically generated and specifically targeted as the last button

Is there a way to enable the plusSign = true option only for the last item in the dynamic input field? (function() { var app = angular.module('managementApp', []); // var app = angular.module('managementApp', ['ngRoute' ...

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

Reading data from Firestore in Next.js

I came across a Next.js starter that retrieves data from Firestore v9, but it only displays the data after a click event. How can I modify this code in Next.js to automatically show the data without needing to click? import { db } from '@/lib/firebase ...

Dynamic controller in TypeScript with React Hook Form

Is there a way to ensure that the fieldName is always inside the control? Passing a field name that doesn't exist in the form causes issues for me, so I'm looking for a solution. Can anyone help? import { Control, Controller } from 'react-ho ...

What steps do I need to take to export my TypeScript declarations to an NPM package?

I have multiple repositories that share similar functionality. I want to export type declarations to an NPM package so I can easily install and use them in my projects. Within the root directory, there is a folder called /declarations, containing several ...

What is the option for receiving automatic suggestions while formatting components in a react.js file?

When styling elements in our app using app.css or styles.css, VS Code provides auto-suggestions. For example, if we type just "back" for background color, it will suggest completions. However, this feature does not work in react.js or index.js. Why is that ...

Unable to retrieve the chosen option from the datalist

I am encountering an issue with a datalist where I can't seem to retrieve the value that is currently selected when a button is clicked. Despite following recommendations from various posts on Stack Overflow, my code still returns undefined. Interesti ...

Deactivate a button when clicked on a card that has been mapped

After creating a card component and mapping through each card, I added an onClick function to disable the button of the clicked card. However, my logic ended up disabling all buttons instead. Here is the code snippet where I define the rendering of the UI ...

Unable to show <LI> elements

I'm having trouble adding LI items to the #historial <UL> tag. Whenever the for loop is inside the function, the list displays with some elements duplicated. I believe the for loop should remain outside of the function. Could someone please he ...

Error encountered in Storybook: The value is not iterable (property Symbol(Symbol.iterator) cannot be read)

I recently created a React library using and opted for the React + TypeScript + Storybook template. You can find the entire codebase here → https://github.com/deadcoder0904/react-typical I encountered the following error: undefined is not iterable ( ...

"Experiencing sluggish performance with VSCode while using TypeScript and Styled Components

My experience with vscode's type-checking is frustratingly slow, especially when I am using styled components. I have tried searching for a solution multiple times, but have only come across similar issues on GitHub. I attempted to read and understa ...