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

Developing a REST API for a component with 18 interconnected elements

Currently, I am developing a REST API to expose a table to an Angular frontend, and I've encountered a unique challenge: The data required for display is spread across 10 different tables besides the main entity (referred to as "Ticket"). Retrieving t ...

Body not being checked for overloads

Is there a way for TypeScript to validate the function body against function overloads? Despite having multiple signatures, it seems that the function implementation is not being checked properly: function a(input: string): string function a(input: number ...

What could be causing the failure of the subscribe function to interpret the API response

I want to retrieve user information by using their identification number through a method component.ts identificacion:any = this.route.snapshot.paramMap.get('identificacion'); constructor(private route: ActivatedRoute, private dataService: ...

When using Ionic 3 on an Android device, the keyboard is causing the tabs and app content to shift upwards

I'm currently working on an Ionic 3 app and encountering a problem. Whenever I click on the search function, the keyboard opens and pushes all the content of the app to the top. Here is the code for the tabs and view: <ion-tabs color='navbar ...

Can you explain the significance of the ellipsis in @NGRX for Angular?

Can you explain the significance of these three dots and why they are necessary? export function leadReducer(state: Lead[]= [], action: Action { switch(action.type){ case ADD_LEAD: return [...state, action.payload]; case R ...

What could be causing the Angular router outlet to not route properly?

Check out this demo showcasing 2 outlets (Defined in app.module.ts): <router-outlet></router-outlet> <router-outlet name="b"></router-outlet> The specified routes are: const routes: Routes = [ { path: 'a', com ...

Angular component fails to render when passed as a string in the innerHtml attribute

One interesting challenge I faced is working with an API that returns HTML containing Angular components which are not being displayed in the application. I am trying to figure out how to display an Angular component stored as a string within the HTML con ...

Guide to configuring a not null property in Typescript Sequelize:

Hello there! I am trying to figure out how to set a not null property using TypeScript Sequelize. I have tried using the @NotNull decorator, but unfortunately it does not seem to be working. The errors I am encountering are as follows: Validation error: W ...

Error in JSON format detected by Cloudinary in the live environment

For my upcoming project in Next.js, I have integrated a Cloudinary function to handle file uploads. Here is the code snippet: import { v2 as cloudinary, UploadApiResponse } from 'cloudinary' import dotenv from 'dotenv' dotenv.config() ...

Serving HTML from NodeJS instead of JSON

I have implemented two middleware functions import { NextFunction, Request, Response } from 'express'; const notFoundHandler = (req: Request, res: Response, next: NextFunction) => { const error = new Error(`Page Not Found - ${req.originalUr ...

Adding additional properties to Material UI shadows in Typescript is a simple process that can enhance the visual

https://i.stack.imgur.com/9aI0F.pngI'm currently attempting to modify the Material UI types for shadows, but encountering the following error when implementing it in my code. There is no element at index 25 in the tuple type Shadows of length 25. I&a ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Zero-length in Nightmare.js screenshot buffer: an eerie sight

I'm currently working on a nightmare.js script that aims to capture screenshots of multiple elements on a given web page. The initial element is successfully captured, but any subsequent elements below the visible viewport are being captured with a l ...

Developing a loader feature in React

I've been working on incorporating a loader that displays when the component has not yet received data from an API. Here's my code: import React, {Component} from 'react' import './news-cards-pool.css' import NewsService fro ...

Since making the switch from Angular 5 to 6, I've been consistently encountering a frustrating issue: the error message "timers in xml2js cannot

As mentioned in the title, I am constantly encountering a strange error. Despite attempting to uninstall it using npm uninstall xml2js, nothing has proven effective thus far. https://i.stack.imgur.com/DccM7.png ...

Is there an alternative to RequestOptionsArgs that I can use in this function?

I am currently working on updating an existing Angular application from version 4.3 to Angular 8. One of the challenges I'm facing is replacing old component classes like ConnectionBackend, RequestOptions, and RequestOptionsArgs with their updated equ ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

What are some strategies for enhancing TypeScript/Node speed in VSCode with the help of WSL2 and Docker?

My development environment consists of VSCode running on Windows (v1.58.2) with the Remote WSL extension (v0.58.2). I have Docker Desktop (3.5.2, engine: 20.10.7) set up to work with Linux containers through the WSL2 backend. Within these containers, I a ...

Running PM2 with Angular-CLI is a great way to ensure your Angular2 project runs smoothly and efficiently

Is there a way to run ng serve --prod with pm2 on DigitalOcean for an Angular 2 project? I attempted to use http-server -p 4200 -d false in the dist/ folder after running ng build --prod, but when I try to access the website , I encounter a 404 error (eve ...

What is behind the occurrence of the 'createObjectURL' error?

I am attempting to capture an image using the camera on my laptop. Previously, it was functioning flawlessly, but now I am encountering an error in my console: ERROR Error: Uncaught (in promise): TypeError: Failed to execute 'createObjectURL&apo ...