An unexpected error causes the entire application to come to a halt, specifically due to a property being undefined. Assistance is

Issue Reproduction:

1. We have a list of advertisers (our clients) for whom we run various marketing campaigns.

2. Upon clicking the "Campaign" button for a specific advertiser.

Result: You are taken to the "campaigns" page displaying all campaigns for the selected advertiser.

3. However, sometimes, but not always, after clicking the "Campaign" button, an error occurs stating "name" is undefined. Screenshot: https://i.sstatic.net/fRiHl.png

Below is the main logic executed upon clicking the "Campaign" button.
header.component.ts:

@Input() advertiserId: string;
@Input() advertiserIoId: string;
@Input() campaignId: string;

public advertiserDto: AdvertiserDto;
public advertiserIoDto: AdvertiserIoDto;
public campaignDto: CampaignDto;

constructor(private advertiserModel: AdvertiserModel,
            private advertiserIoModel: AdvertiserIoModel,
            private campaignModel: CampaignModel) {
}

 ngOnChanges() {
    this.getAdvertiserDto();
    this.getAdvertiserDtoData();
    this.getAdvertiserIoDto();

    // Here lies the issue in getAdvertiserIoDtoData()
    this.getAdvertiserIoDtoData();
    this.getCampaignDto();
    this.getCampaignDtoData();
}

private getAdvertiserDto(): void {
    this.advertiserDto = this.advertiserModel.getDto(this.advertiserId);
}

private getAdvertiserIoDto(): void {
    this.advertiserIoDto = this.advertiserIoModel.getDto(this.advertiserIoId, this.advertiserId);
}


private getCampaignDto(): void {
    this.campaignDto = this.campaignModel.getDto(this.campaignId, this.advertiserId, this.advertiserIoId);
}

private getAdvertiserDtoData(): void {
    this.advertiserModel
        .getDtoData(this.advertiserDto)
        .catch(error => console.log(error))
}

private getAdvertiserIoDtoData(): void {
    this.advertiserIoModel
        .getDtoData(this.advertiserIoDto)
        .catch(error => console.log(error))
}

private getCampaignDtoData(): void {
    this.campaignModel
        .getDtoData(this.campaignDto)
        .catch(error => console.log(error))
}

header-template - part ({{ advertiserIoDto.dtoData.name }}) - where dtoData.name is undefined:

<span *ngIf="campaignDto.isLoaded === true"
  [routerLink]="['/private/advertiser/' + advertiserId + '/advertiserIo/' + advertiserIoId]"
  class="nano-breadcrumb-item">
  {{ advertiserIoDto.dtoData.name }}
</span>

Another important observation: When comparing the execution order in "ngOnChanges" and the "Browser", you'll notice that "getAdvertiserDtoData()" starts before "getCampaignDtoData()" but executes later. This could be the issue.

Screenshot: https://i.sstatic.net/uRU5X.png

Any suggestions on how to resolve this?

Error Trace:

NanoCampaignHeaderComponent.html:16 ERROR TypeError: Cannot read property 'name' of undefined
at Object.eval [as updateRenderer] (NanoCampaignHeaderComponent.html:16)
at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13105)
at checkAndUpdateView (core.es5.js:12256)
at callViewAction (core.es5.js:12599)
at execEmbeddedViewsAction (core.es5.js:12557)
at checkAndUpdateView (core.es5.js:12252)
at callViewAction (core.es5.js:12599)
at execComponentViewsAction (core.es5.js:12531)
at checkAndUpdateView (core.es5.js:12257)
at callViewAction (core.es5.js:12599)

Answer №1

Sharing my insights: when working with Javascript, you have the ability to write conditions in a way that they produce values as output.

For example:

let obj = { a: true, b: true };
console.log(obj.a && obj.b);

What do you expect to see? Most likely, true will be displayed:

let obj = { a: true, b: true };
console.log(obj.a && obj.b);

However, in reality, it doesn't show the boolean result: it shows the last value of the condition. This concept becomes clearer with strings:

let obj = { a: 'A', b: 'B' };
console.log(obj.a && obj.b);

Now, you might expect to see true again (due to truthy and falsy values). But consider this:

let obj = { a: 'A', b: 'B' };
console.log(obj.a && obj.b);

B is displayed. As mentioned, the last value of the condition is what is returned.

Why am I telling you this? Simply because when you write this

advertiserIoDto?.dtoData?.name

It is essentially a shorthand for this

advertiserIoDto && advertiserIoDto.dtoData && advertiserIoDto.dtoData.name

Which means, if you grasp it, that advertiserIoDto.dtoData.name will be the final output.

And then, there is an OR statement:

{{ advertiserIoDto?.dtoData?.name || '' }}

This also ties back to the same concept: when all values are falsy, the OR statement is returned. Let me demonstrate with an example:

let obj = { a: '', b: '' };
console.log(obj.a && obj.b || 'No value');

Because '' is falsy, none of the conditions are met: the code returns the OR statement.

This principle applies in Angular as well: the safe navigation ? in HTML functions as a shortcut for this behavior.

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

What is the consensus on incorporating client-side routing in conjunction with the server-side routing features offered by angular-universal

I am diving into the world of Angular Universal and exploring 'isomorphic' javascript for the first time. I am a bit puzzled about how to set up a logical routing system. Should I treat Angular Universal as a typical Node.js REST API? Or is its ...

When using Next.js getServerSideProps(), cookies are not accessible on the initial render after a redirect, but they become available upon refreshing the page

Within my Next.js application, I am serving cookies from the server-side API like this: res.setHeader('Set-Cookie', AJWT) res.redirect(302, '/') Now, in my index.js file, I am attempting to retrieve the cookie before the page is render ...

The useEffect hook in Next.js does not trigger a re-render when the route changes

I'm currently experiencing an issue with a useEffect inside a component that is present in every component. I've implemented some authentication and redirection logic in this component, but I've noticed that when using Next.js links or the b ...

Having trouble fetching results from AJAX objects using vanilla JavaScript?

I am currently working on developing my own AJAX prototype without relying on jQuery or any other libraries. However, I am facing an issue where I cannot retrieve any results and the breakpoint set on a specific line is not triggering: The problem seems t ...

The server appears to be active, but there is a lack of content rendering when using React, Node

When I attempt to run the code in app.jsx, nothing displays even though the index.html is functioning properly. Code from Server.js: var express = require('express'); server.js page var app = express(); app.use(express.static('public' ...

Sending an image dynamically as a prop to a child component

Within my parent component, I retrieve an object from an API which I later enhance with an image as a key/value pair. Subsequently, I pass this modified object to a child component for rendering. In order to accomplish this, I referred to the following pos ...

Is it possible to generate multiple modal windows with similar designs but varying content?

I am facing a challenge with 140 link items that are supposed to trigger a modal window displaying a user profile for each link. The issue is that each user profile contains unique elements such as three images, a profile picture, text paragraph, and socia ...

Issue with CSRF token validation in ASP.NET Core when integrating with Angular

To enhance the security of my application, I decided to implement CSRF-Token protection using Angular documentation as a guide. According to the Angular docs, if a cookie named XSRF-TOKEN is present in the Cookies, it will automatically be included in the ...

Establish a Connection Between Local Mongo Database and Your Application

I have successfully set up a local MongoDB connection with a React, GraphQL application. All configurations are in place and functioning properly as far as I can tell. To visually view my MongoDB databases, I have installed Compass. The content of the Ser ...

Empty Array result from push operations during Node.js/Express GET request

Currently, I am in the process of coding a function that involves calling an API to fetch URLs. Below are the specific steps I aim to achieve: Take in an array of objects (specifically restaurants) as input Initiate a call to the Google Search API for ea ...

Utilize an object model property as an array key for filtering in the AngularJS and MEANJS framework

I am currently working on a MEANJS application that includes a CRUD module for countries. When I select a country from the default list view, it redirects me to the view-country.client.view page. In order to enhance my model, I have introduced a field name ...

Spring Boot - The Cross-Origin Resource Sharing filter is effective for handling GET requests, however it does not properly handle other

In my current project, I am working on a Spring Boot 2.2.5 application paired with an Angular 9 frontend. One of the challenges I have faced is configuring a CORS filter in the Spring Boot backend to allow any origin, headers, and requests. After thoroug ...

Guide to creating a Map with typescript

I've noticed that many people are converting data to arrays using methods that don't seem possible for me. I'm working with React and TypeScript and I have a simple map that I want to render as a list of buttons. Here is my current progres ...

The given 'FC<ComponentType>' type argument cannot be assigned to the 'ForwardRefRenderFunction<unknown, ComponentType>' parameter type

Currently, I am using react in conjunction with typescript. Within my project, there are two components - one serving as the child and the other as the parent. I am passing a ref to my child component, and within that same child component, I am binding my ...

Exploring Typescript for Efficient Data Fetching

My main objective is to develop an application that can retrieve relevant data from a mySQL database, parse it properly, and display it on the page. To achieve this, I am leveraging Typescript and React. Here is a breakdown of the issue with the code: I h ...

Can you explain the significance of the symbol ! when declaring a variable in TypeScript?

Currently, I am delving into an Angular project and came across a peculiar line of code in the component.ts file provided by my instructor. @Input() public searchType!: string; This line resides within the OnInit() function of the component's TypeScr ...

Encountering an error while trying to launch Chrome with Puppeteer

Currently, I have set up an elastic-beanstalk instance on AWS and am in the process of creating a pdf export feature on a dashboard using Puppeteer. Although I have successfully tested the application locally, I encountered an error when attempting to run ...

What are some tips for efficiently troubleshooting a JQuery GET request to MailChimp 3.0 servers?

I am encountering an issue while trying to include users' emails in my Mailchimp 3.0 audience list. I am making a GET request using JQuery, but I keep running into the following error: {"type":"http://developer.mailchimp.com/documentation/mailchimp/g ...

Is it possible for me to avoid html tags inside a class without using the xmp tag?

There are a few ways to approach this question. It's important to decide which method will be most beneficial for your specific needs... Is it possible for JavaScript to recreate the deprecated <xmp> tag using an "xmp" class? Can we replicate ...

Display JSX using the material-ui Button component when it is clicked

When I click on a material-ui button, I'm attempting to render JSX. Despite logging to the console when clicking, none of the JSX is being displayed. interface TileProps { address?: string; } const renderDisplayer = (address: string) => { ...