Unable to retrieve property values from an array containing objects

I am encountering an issue with my Angular + ngrx setup, and the following output is displayed in the console:

{status: true, rows: 1, data: Array(1)}
data: Array(1)
0: {id: "Q", description: "QQQQQ", is_active: true, created_at: "2021-02-05T01:24:21.594Z", updated_at: "2021-02-05T01:24:21.594Z"}
length: 1
__proto__: Array(0)
rows: 1
status: true
__proto__: Object

However, I am unable to access the properties of the object inside the array such as id. To address this, I have defined an interface like so:

export interface TipoDocumentoResult {
    status: boolean;
    rows: number;
    data: TipoDocumento
}

The 'TipoDocumento' class is structured as follows:

export class TipoDocumento {
    constructor(
        public id: string,
        public description: string,
        public is_active: boolean,
        public created_at: Date,
        public updated_at: Date,
    ) { }
}

This is how I have configured my ngOnInit function:

this.store.pipe(
      select('tipoDocumentoGetOne'),
      filter(({ loading, loaded }) => loading === false && loaded === true),     
    ).subscribe(
      ({ data }) => {
        this._result = data
        this._data = this._result?.data
        console.log(this._result)
        console.log(this._data[0]) // At this point, I encounter an error
      }
    );

Upon running this code, the following message appears:

Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'TipoDocumento'. Property '0' does not exist on type 'TipoDocumento'

I apologize for any confusion in my explanation.

Warm regards

Answer №1

Seems like you have already destructured your object in the subscribe method:

 ({ data }) => { // variable 'data' is already of type DocumentType 

Essentially, you are indicating that an object is coming in with a 'data' field and you only care about that specific field. If you rename 'data' in your subscribe, you should encounter a compilation error.

I believe what you actually need is this:

this.store.pipe(
      select('DocumentType'),
      filter(({ loading, loaded }) => loading === false && loaded === true),     
    ).subscribe(
     result => {
        this._result = result 
        this._data = this._result?.data
        console.log(this._result)
        console.log(this._data[0]) // Here, I encounter an error message
      }
    );

As a note for NGRX: Using classes (like DocumentType) in the NGRX Store can be risky as ensuring immutability becomes challenging and Helper Frameworks like NGRX Entity might convert the class into a plain JavaScript object.

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

An argument error in IE 8 caused by an invalid procedure call

Is there a way to access the opener's class in a child window created using window.open? This works smoothly in W3C browsers, but fails in IE 8. On the other hand, I tested using an iframe and it seems to work fine across all browsers. The main goal o ...

Tips for testing Observable.fromEvent

Can you provide a method to test Observable.fromEvent using jasmine? @ViewChild('d') private inputDatePicker: NgbInputDatepicker; this.subscription = Observable.fromEvent(document, 'click').subscribe((event: KeyboardEvent) => { ...

Forward the value of the selected radio button

Currently, I am focusing on this code snippet. <html> <script> var submit = document.getElementById('btnFormSubmit'); submit.addEventListener('click', submitForm); function submitForm(event){ event.preventDefault(); event. ...

Looking forward to the nested forEach functionality

Can you explain why this code snippet behaves unexpectedly? const firstArray = ['toto', 'toto']; const secondArray = ['titi', 'titi']; firstArray.forEach(async (toto, i) => { await secondArray.forEach(async tit ...

Searching for information in one array using a loop with another array (MongoDB and JavaScript)

I have two arrays that need to be compared for matching elements. let firstArray = [1, 2, 3] let secondArray = [{id:1}, {id:1}, {id:3}] I am trying to create a new array containing objects with the same id. Despite trying different approaches, I am unabl ...

How to manually remove an Angular directive

Is it possible to manually remove a directive? For instance, if I need the directive to perform a task once and then be cleared from memory. @Directive({ selector: '[doSomething]' }) export class DoSomethingDirective { constructor(private ...

Tips for preserving login status even after the browser is shut down with the help of JavaScript

I need help with maintaining a user session in my chat application even when the browser is closed. After users log in for the first time, I want their credentials to be remembered by the browser (I'm currently using local storage). How can I ensure ...

typescriptCreating a custom useFetch hook with TypeScript and Axios

I have a query regarding the utilization of the useFetch hook with TypeScript and Axios. I came across an example of the useFetch hook in JavaScript, but I need help adapting it for TypeScript. The JavaScript implementation only handles response and error ...

Tips for extracting elements from an HTML document using Angular

I seem to be facing a small issue - I am trying to develop a form using Angular. Below is my HTML: <form [formGroup]="requeteForm" (ngSubmit)="ajouter()" *ngIf=" tables!= null"> <div class="form-group&quo ...

Is it possible to disable the next and previous buttons in jCarousel?

I am currently using the jCarousel slider from for my website. The slider displays one image at a time, with a total of four images. I want to hide the previous arrow when displaying the first image and hide the next arrow when displaying the fourth image ...

Using Angular 2 to implement a custom dropdown feature with the ngModel directive

I've created a unique custom component that displays employment types in a dropdown menu and allows the user to select one. Here is the code for the component: import { Component, OnInit } from "@angular/core"; import { EmploymentType } from '. ...

Exploring the Depths of Angular Reactive Forms with Recursion

Dealing with recursion and form groups app-root.component.html <div [formGroup]="form"> some content <app-root></app-root> </div> Is it possible to implement the same form group and form controls in my recursive structure? For ex ...

Utilizing jQuery to eliminate a script function from an external webpage

Currently, I am utilizing a ColdFusion script to load an external page within the container tag. This external page contains a sorting function defined as: function sorting(sortid). However, this function's sorting criteria constantly leads to errors ...

Maximizing Redux DevTools integration with Redux Toolkit and Next.js for TypeScript projects

The initial state is visible in the DevTools, but any actions taken after the code has rendered do not show up. In pages/_app.tsx, I have implemented the following: import getStore from '../store/store' export default function MyApp({ Component ...

I encountered an issue while using the tab bar feature in Bootstrap where I wasn't able to navigate back to the first tab or any

My current project involves JavaScript, and I integrated a Bootstrap tab bar component. However, when I try to run the code in Google Chrome, I encounter an issue. The first time I select the first tab, the content displays correctly. But when I select the ...

Generate a new component within another dynamically generated component

In my endeavor to dynamically create a component within another dynamically created component, I am facing a unique challenge. Below is the code snippet: export class DefaultLayoutComponent { constructor(private cdRef: ChangeDetectorRef, public defa ...

Inquiry Concerning AJAX Frameworks Such as DWR

My web app currently relies on an AJAX library called DWR to dynamically fetch data. When a user clicks on certain table items, a DWR call is made to retrieve details for that item in the form of complete HTML code as a string. Behind the scenes, a Java me ...

Warning: An unhandled promise rejection occurred while using agenda

I encountered an UnhandledPromiseRejectionWarning while running my project which utilizes the agenda package. Here is the code snippet: agenda.define('transferDBField', (job, done) => { if (this.tPrice) { this.prices.push(this.tP ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

Maximizing the Efficiency of jQuery and Javascript Frameworks

Currently, I am working on a project that involves utilizing a JavaScript framework (jQuery) in conjunction with various plugins (validation, jquery-ui, datepicker, facebox, and more) to enhance the functionality of a modern web application. However, I ha ...