Utilizing NGRX Entity for Selector-Based Filtering in Angular

My goal is to extract the payload data based on a specific property.

 //reducer.ts

  case MessagesActionTypes.LOAD_Message_SUCCESS: {
      console.log('reducer='+ 
      JSON.stringify(action.payload.Messages));//data received here
      return adapter.addAll(action.payload.Messages, state);
    }

    export const getSelectedMessageId = (state: MessageState) => state.selectedMessageId;

// get the selectors
const { selectIds, selectEntities, selectAll, selectTotal } = adapter.getSelectors();


// select the array of Messages
export const selectAllMessages = selectAll;

Here is the selector being used:

 //     Selector.ts

export const selectHomeQueues = createSelector(
  fromReducer.selectAllMessages,
 (messages) => messages.filter(message => message.queue === 'HOME')
 );

In the reducer, I am able to receive data, but when running the selector, I encounter an error:

ERROR TypeError: Cannot read property 'map' of undefined

Note: I have not been able to locate any examples of filtering in NGRX entity selectors.

How can we effectively filter selectors in NGRX entity?

Answer №1

I encountered the same problem too. To resolve it, make a slight adjustment to your selector as follows:

export const selectHomeQueues = createSelector(
  selectAllMessages,
 (messages) => messages.filter(message => message.queue === 'HOME')
 );

In this code snippet, selectAllMessages is defined as a simple selector like so:

export const selectAllMessages = createSelector(
  fromReducer.selectAllMessages
 );

We initially attempted to handle this using the adapter, but I believe there may have been a small mistake or misunderstanding made in the process.

This issue arose after upgrading either Angular or Redux, although the exact version numbers are unknown.

Answer №2

If you are encountering the error message "Cannot read property 'map' of undefined," it may be due to an error in another part of your code since there is no reference to 'map' in the code snippet provided in your question.

Upon inspection, it seems that in your selector, you are filtering based on messages but passing header which is not being utilized. It appears that you are filtering message queues rather than individual messages. A corrected version of the code snippet could look like this:

export const selectHomeQueues = createSelector(
  fromReducer.selectAllMessages,
  (messages) => messages.queue === 'HOME'
);

Answer №3

I believe this method could be effective:

const fetchHomeQueues = (store) => {
    return store.select(fromReducer.selectAllMessages)
        .filter(message => message.queue === 'HOME')
}

To implement it, simply call:

fetchHomeQueues(this.store).subscribe(...)

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

Using pinia always results in undefined arrays within the state

Pinia has been a crucial part of my Vue3 projects, and I've encountered a dilemma while trying to store temporary data in Pinia. Here's a snippet from my store file: // template.ts export const useTemplateStore = defineStore('template', ...

ngIf not working properly with the updated value of [(ngModel)]

I am encountering an issue with a select element that has options. The select is using the [(ngModel)] directive to save selected values into "rightFieldTypeId." I have elements that should be displayed based on the value of "rightFieldTypeId." Even though ...

Navigate to a new page by utilizing the nav.push function while incorporating a side menu in your

Trying to develop a small application using ionic2 to enhance my understanding of it, however, facing some challenges with navigation. I've grasped the distinction between a rootpage (adjusted with nav.setRoot) and a regular page (added through nav.p ...

Is it possible to implement a page transition using preact?

I've been experimenting with creating a page transition using preact-router. I attempted to use the preact-transition-group package along with the preact-css-transition-group package, but encountered an error. Despite this, here is my basic setup: imp ...

Merge two observables together to create a single observable that emits values from both sources. Only one observable will emit values

I am looking to combine two observables of type T[] obtained from httpservice. I have tried using forkJoin and zip, but they both return an Observable of type [T[], T[]]. However, I want to receive an object of type T[] as shown in the following code snip ...

Sign up for websocket topics and establish numerous connections

When multiple components share a WebSocket connection, it results in duplicate connections. export class NotificationService { notification; destroy$ = new Subject(); constructor(private appService: AppService) {} createWs() { this.notificati ...

Angular 2 - Troubleshooting Issues with Nested Components and @Input Propagation

The Logic by IMG I'm facing an issue with updating child component variables in real-time. I attempted to use @Input, but it only gets initialized and doesn't change over time. Parent Component <div> <h4>Рэйтынг : {{video ...

The argument labeled as 'Subscription' cannot be assigned to the parameter labeled as 'string' in Angular

I am utilizing my Subscription variables to retrieve the API from configuration settings. public ChannelsAPI=this._configservice.getConfiguration("ChannelAPI").subscribe((result) => console.log(result)); This is the method _Configservice.getC ...

TS1316 Error: You can only have global module exports at the top level of the file

Encountering difficulties while trying to compile an older typescript project that I am revisiting. The build process is failing due to an issue with q. I suspect it may be related to the tsc version, but no matter which version I try, errors persist. Som ...

Troubleshooting the issue of 'is not a function' in browsers when using TS Namespaces

Currently diving into the world of TypeScript, I've embarked on the journey of organizing my code into separate files. My primary file is structured as follows: // calculator.ts namespace Calculator { console.log(Calculator.operate(1,2,"+")) } In ...

Is it possible to import both type and value on the same line when isolatedModules=true?

Did you know with Typescript, you can do type-only imports? import type { Foo } from "./types" If the file exports both types and values, you can use two separate import statements like this: import type { Foo } from "./types"; import ...

Attempting to implement a typeguard in Typescript that relies on the presence of specific content within an element

Currently, I am attempting to develop a Typescript conditional that verifies if a particular word is already present in the name. The function in question is as follows: isOrganic() { for (let i = 0; i < this.items.length; i++) { if(this.ite ...

Ways to stop the MasterComponent from rendering on every route change

I have a dropdown menu: click here to view My goal is to keep the dropdown open when the user opens a menu, but disable it if the user changes routes by clicking on another menu. How can I achieve this? Note: If the user navigates within the same route, ...

Firing an Event with a specific target value using Jasmine

Is there a way to trigger a change event in a Jasmine unit test with the inclusion of a target.value? The component being tested contains a method similar to this: @HostListener('change', ['$event']) onChange(event) { const value = e ...

Using Typescript with NodeJs

As I work on my app.ts file, I prefer using this approach. However, I’ve been encountering some problems with .d.ts imports, which are preventing me from accessing the full API of express. The main issue is that in Webstorm2016 (I haven’t tested it on ...

Webpack converts 'import' statements to 'require'

I'm currently in the process of compiling my nodeJS project using webpack. Everything seems to be working correctly after compilation, but I've noticed that the imports are being changed to requires. This causes an error when trying to run index. ...

Ways to detect button click in a separate component

I am working with an Angular app that consists of two components: a navbar component and a display component. The navbar component has a search button that, when clicked, searches for the entered name and displays the details in the display component. I ne ...

Angular binding and date validation - a powerful combination!

Facing an issue with date properties in Angular. For instance, here is the Model I am working with: export class Model{ dateFrom Date; dateTo Date; } In my Create view, I have the following setup: <input type="date" [(ngModel)] = "model.dateFrom"> ...

Verify whether a specific value exists in my React array; if it does, display a specific component

I need to display different components based on the following criteria: Whether the items contain a specific value And if all 10 items have that value const DisplayComponents = ({ data }: Props) => { const filteredItems = data.items?.filter( ( ...

Create a hierarchical tree structure using a string separated by dots

I am struggling with organizing a tree structure. :( My goal is to create a tree structure based on the interface below. export type Tree = Array<TreeNode>; export interface TreeNode { label: string; type: 'folder' | 'file'; ...