The application was not functioning properly due to an issue with the getSelectors() function while utilizing @ngrx/entity to

Currently, I am facing an issue with implementing a NgRx store using @ngrx/entity library. Despite Redux Devtools showing my collection loaded by Effect() as entities properly, I am unable to retrieve any data using @ngrx/entity getSelectors. Thus, it seems that my Effect is working correctly. Now, my goal is to select the data as an array by utilizing the selectAll selector from adapter.getSelectors() function in my reducer index setup.

reducers/index.ts

import { ActionReducerMap, createFeatureSelector, createSelector } from '@ngrx/store';

  import * as fromModels from './models.reducer';
  import { EntityState } from '@ngrx/entity';

  export interface State {
    models: fromModels.State;
  }

  export const reducers: ActionReducerMap<State> = {
    models: fromModels.reducer
  };

  export const getModelsState = createFeatureSelector<fromModels.State>('models');
  export const { selectAll: getAllModels } = fromModels.adapter.getSelectors(getModelsState);
  

reducers/models.reducer.ts

import { createFeatureSelector, createSelector } from '@ngrx/store';
    import { createEntityAdapter, EntityState, EntityAdapter } from '@ngrx/entity';
    
    import { ModelsActions, ModelsActionTypes } from '../actions';
    import { Model } from '../../models/model';
    
    export const adapter: EntityAdapter<Model> = createEntityAdapter<Model>({
      selectId: model => model.id,
      sortComparer: (modelA, modelB) => modelA.id === modelB.id ? 0 : (modelA.id === modelB.id ? 1 : -1)
    });
    
    export interface State extends EntityState<Model> {}
    const initialState = adapter.getInitialState();
    
    export function reducer(state = initialState, action: ModelsActions): State {
      switch (action.type) {
    
        case ModelsActionTypes.LoadSuccess:
          return adapter.addAll(action.payload, state);
    
        default: return state;
      }
    }
  

In my container component, I attempt to select the data using the ngrx/entity selector and display the data using the async pipe. Here is a shortened version of the template:

models.component.ts

// All other import statements
    import { Store, select } from '@ngrx/store';
    import * as fromFeature from '../store';
    
    @Component({
      template: `{{models$ | async}} | json`
    })
    export class ModelsComponent implements OnInit {
      models$: Observable<Model[]>;
    
      constructor(private store: Store<fromFeature.State>) {}
    
      ngOnInit() {
        this.models$ = this.store.select(fromFeature.getAllModels);
        this.store.dispatch(new fromFeature.LoadModels());
      }
    }
  

The console returns an error message:

ModelsComponent.html:2
    ERROR TypeError: Cannot read property 'ids' of undefined
    at selectIds (entity.es5.js:45)
    at eval (store.es5.js:572)
  

I would appreciate any suggestions or ideas on how to resolve this issue. Thank you!

UPDATE [Requested template]

The template simply subscribes to the models$ observable, following the same logic as in the previous template. The model-card.component.ts only receives Input()'s and ng-content.

Answer №1

Aha, I finally cracked the code. The issue was with the createFeatureSelector function, which does exactly what its name implies - selects features. I had registered the module using

StoreModule.forFeature('configuration', reducers)

The workaround involves fetching the ConfigurationState from the Feature selector and the models state from the default selector.

reducers/index.ts

[...]
export const getConfigurationState = createFeatureSelector<ConfigurationState>('configuration');
export const getModelsState = createSelector(
  getConfigurationState,
  (configuration) => configuration.models
);

export const {
  selectIds,
  selectEntities,
  selectAll
} = fromModels.adapter.getSelectors(getModelsState);

Many thanks for your valuable assistance!

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 reason behind Typescript flagging a potential undefined value when checking for array length using a greater than comparison but not with an

Consider the following excerpt from a React component: const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => { const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : t ...

What is the best way to implement a custom layout with nuxt-property-decorator?

Summary of Different Header Components in Nuxt In order to set a different header component for a specific page in Nuxt, you can create separate layout files. layout ├ default.vue // <- common header └ custom.vue // <- special header for s ...

Implementing a universal (click) attribute for Angular 2 in CSS

When using Angular 1, it was as easy as following this syntax: [ngClick], [data-ng-click], [x-ng-click] { cursor: pointer; } This snippet ensured that any tags with the ng-click attribute displayed a pointer cursor. How can we achieve the same effect ...

Angular 5 Component persists despite change in child route

Hello, I'm facing an issue with my Angular 5 App. I have created a simple app with component routing structured as follows: { path: '', component: SetupComponent, pathMatch: 'full' }, // landing page { path: 'setup', com ...

Exporting key/value objects with React components as values in Typescript

I have a .tsx file where I need to export an object containing key/value pairs. Each value is going to be a React component used in another file. While I will have multiple key/value pairs, I'm focusing on just one at the moment. object.tsx import { ...

Issue with reducer not being executed in my Redux configuration

After experimenting with the default setup from CRA, I came across a tutorial on freeCodeCamp that I followed to set everything up. However, I noticed that the reducer is not being called as expected. In its current state, when I click the image, the class ...

What method can be used to seamlessly integrate Vue.js into a TypeScript file?

The focus here is on this particular file: import Vue from 'vue'; It's currently appearing in red within the IDE because the necessary steps to define 'vue' have not been completed yet. What is the best way to integrate without r ...

What are the steps to restrict a user from accessing a specific website?

In my Vue.js project, I've implemented a function that hides a specific menu item for users with insufficient permissions: <a :href="href" @click="navigate" v-if="hideMenuItem()"> // some code </a> hideMe ...

The 'length' property is not found within the 'HTMLElement' type

Can someone assist me with looping over the number of nav-items I have? I am encountering an error that says: Property 'length' does not exist on type 'HTMLElement'. I understand that changing document.getElementById('nav-item) to ...

Using React with Typescript: Passing Props and Defining Data Types

As a relatively new TypeScript enthusiast, I find myself facing some challenges. Specifically, I am struggling with errors in my code and uncertain about how to properly pass props and select the correct type. Any guidance on this matter would be greatly a ...

What is the best way to establish a restriction on the number of items obtained from an RSS

I am receiving a feed from this specific link. My goal is to only retrieve the initial five items from the feed, but currently I am getting all of the items. Is there a way for me to specifically request only the first five items? Do I need to include an ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...

Retrieving data from a JSON using Typescript and Angular 2

Here is an example of what my JSON data structure looks like: { "reportSections": [ { "name": "...", "display": true, "nav": false, "reportGroups": { "reports": [ { "name": "...", "ur ...

Discover the power of sharing a service instance in Angular 2 RC5

In the past, I shared a service instance by declaring it as a viewInjectors within my @Component like so: @Component({ selector: 'my-sel', viewInjectors: [SharedService], templateUrl: 'template.html', pipes: [MyPipe] }) ...

Error: The AWS amplify codegen is unable to locate any exported members within the Namespace API

Using AWS resources in my web app, such as a Cognito user pool and an AppSync GraphQL API, requires careful maintenance in a separate project. When modifications are needed, I rely on the amplify command to delete and re-import these resources: $ amplify r ...

Tips for adjusting the dimensions of a child element to match its parent in Angular 12 with Typescript

I have included the child component in the parent component and I am displaying that child component within a col-md-8. What I want to achieve is to highlight a specific div in the child component with additional text, making it equal in size to the parent ...

Show an Angular Mat Card beneath the Input Field and position it on top of all other div elements

I am designing a signup page and I need to include a material card below the password field with checkboxes for password requirements. The challenge is that when the card appears, it pushes down all other elements such as the sign-up button. I want the ca ...

Definitions for d3-cloud

I am trying to create a word cloud using d3-cloud in my Angular2 application. However, I am struggling to find the correct typings to install. I attempted to use this package @types/d3.cloud.layout from npm but encountered an issue when importing it into ...

Printing with Angular 2+ using ngx-print extension can be done manually by

Is there a way to print a div in Angular +2 using ngx-print, without automatically triggering the print function through a button attribute like ngxPrint? <button printSectionId="print-section" (click)="printProcedure()">print</button> ...

Angular's HttpClient enables you to easily map an object to an array of properties

I have a scenario where I am calling an API that returns a JSON Object, and my task is to map this object to an array. Despite having the following code, I am not receiving any response or error after making the API call. export class Features { MenuId ...