NGRX refresh does not result in any successful actions

Having an issue with loading users into a mat-selection-list within a form. Everything works fine the first time, but upon page refresh, the selector returns 'undefined'.

Initially, both GET_USERS and GET_USERS_SUCCESS are triggered (console log message 'loadUserTest' is displayed), but on refreshing the page, only GET_USERS is executed without any success or console message.

It seems like there is a problem on the refresh as the effect does not run. The error message in the console reads 'ERROR TypeError: Cannot read property 'users' of undefined', which makes sense, as the selector cannot find any data.

Any insights on what might be causing this issue?

Actions

/*--------------GetAllUsers--------------*/

export class GetUsers implements Action {
readonly type = ActionTypes.GET_USERS;
}

export class GetUsersSuccess implements Action {
readonly type = ActionTypes.GET_USERS_SUCCESS;

constructor(public payload: User[]) {}
}

export class GetUsersError implements Action {
readonly type = ActionTypes.GET_USERS_ERROR;

constructor(public payload: string) {}
} 

Effect

@Effect()
loadUsers$: Observable<Action> = this.actions$.pipe(
ofType(usersActions.ActionTypes.GET_USERS),
switchMap(() => {
  console.log("loadUserTest");
  return (
    this.userResource.getUsers().pipe(
      map((users: User[]) => new usersActions.GetUsersSuccess(users)),
      catchError((err) => {
          console.log("errorTest");
          return of(new usersActions.GetUsersError(err)) }),
    )
  );
  })
);

Reducer

case usersActions.ActionTypes.GET_USERS_SUCCESS: {
  return adapter.addAll(action.payload, {
    ...state,
    loading: false,
    loaded: true,
  });
}

case usersActions.ActionTypes.GET_USERS_ERROR: {
  return {
    ...state,
    entities: {},
    loading: false,
    loaded: false,
    error: action.payload,
  };
}

Selector

import { createSelector } from '@ngrx/store';

import { AppState } from '../../../core/state';
import { adapter } from './users.adapter';

const { selectAll } = adapter.getSelectors();

export const selectState = (state: AppState) => state.user.users;

export const getUsers = createSelector(selectState, selectAll); //Problem!

Create.ts

ngOnInit() {

this.createEventForm();
this.store$.dispatch(new fromUsers.GetUsers());
this.users$ = this.store$.pipe(select(fromUsers.getUsers));
}

Html

<mat-selection-list class="form-group" #selectedUsers formControlName="users">
      <mat-list-option *ngFor="let user of users$ | async" [value]="user">
        {{ user.name }}
      </mat-list-option>
 </mat-selection-list>

Answer №1

It seems like the code you shared doesn't give enough information to identify the issue at hand.

One suggestion I have is to verify the return value after calling this.userResource.getUsers(), just to confirm that it indeed returns an array of users.

If the effect isn't being triggered, then the mention of .users may be limited to the following snippet:

export const selectState = (state: AppState) => state.user.users;

You can try debugging this by ensuring that the state object does contain both user and users.

export const selectState = (state: AppState) => {
  debugger;
  return state.user.users;
};

The root of the problem likely lies within one of these sections.

Answer №2

Hey @CharlieV2, I encountered an issue where I wanted to leverage the effect from one featured store in another featured store, but the effect failed to work when triggered by an action.

To resolve this issue, I successfully imported the necessary effect from the featured store into the module I was working on by using the following code:

EffectsModule.forFeature([featuredEffect, neededFeaturedEffect!])

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

Retrieving the initial row of a specified category using ngFor in Angular 2

My challenge involves working with data in Angular 2. Here is a sample dataset: [ {text: "first", name: "a"}, {text: "rw", name: "a"}, {text: "ds", name: "b"}, {text: "asdf", name: " ...

How can ng-content be used to adjust the displayed content in Angular?

I am working with two components: hostComponent and textComponent. My goal is to project content inside textContent and make modifications based on other input properties. <app-text-component characterCount='5'> <span> Hello World ...

Datatable - pagination - retrieving data from a specific page

Can someone tell me how to retrieve the records from a specific page in a PrimeNG datatable using Angular 2.0? ...

Troubleshooting Angular 2 routes failing to function post aot compilation deployment

Currently, I am implementing RouterModule in my project and have the following configuration in my app.module.ts file: const appRoutes: Routes = [ { path: '', redirectTo: 'mainMenu', pathMatch: 'full' }, { path: 'mainMen ...

Show the attribute of an element in a pop-up window

I have a modal from ngx-bootstrap that I want to display in there a property of my object let's say the name: public students = [ { id: 1, name: 'lorem'} In this button that is common for all entries in the table (each row has this butt ...

The property "state" of RouteComponentProps location does not exist in the provided type {}

We recently encountered a new error that was not present before. Previously, our code compiled without any issues and the compilation process went smoothly. However, individuals who installed the react application from scratch are now facing an error speci ...

Restricting array elements through union types in TypeScript

Imagine a scenario where we have an event type defined as follows: interface Event { type: 'a' | 'b' | 'c'; value: string; } interface App { elements: Event[]; } Now, consider the following code snippet: const app: App ...

Update the component to display the latest information from the Bryntum grid table

In the Vue component, I have integrated a Bryntum grid table along with a bar chart. Clicking on one of the bars in the chart should update the data displayed in the Bryntum grid table. However, I've encountered difficulty in reloading the entire Bryn ...

Managing errors with Angular2 Observables within the HTML template

The updated Angular's use of observables is a game-changer. No more long chains of .done().fail().always() like in JQuery - NG2 simplifies it all with the | async pipe. However, what happens if something goes wrong while loading data for myObservable? ...

assign data points to Chart.js

I have written a piece of code that counts the occurrences of each date in an array: let month = []; let current; let count = 0; chartDates = chartDates.sort() for (var i = 0; i < chartDates.length; i++) { month.push(chartDates[i].split('-&ap ...

Creating a consistent template for typing TypeScript generics

Is it possible to modify a generic function so that it can accept an unlimited number of arguments and concatenate them with .'s? This function should be able to handle nested objects with any number of keys. The current code snippet works when manua ...

In the domain of React and Typescript, a minimum of '3' arguments is anticipated; nonetheless, the JSX factory 'React.createElement' is only equipped with a maximum of '2' arguments. This incongruity is signaled by the

I am facing an error with this particular component: const TheBarTitle = ( theClass: any, columnTitle: string, onClickAction: any, ) => { return ( <div className={theClass} title="Click to add this ...

Angular 6 presents a challenge in rendering data within the multi select drop down feature

I am currently utilizing a multi-select library called ng-multiselect-dropdown in my Angular v6 project. Unfortunately, when I try to display my list using the multiSelect feature, the drop-down shows a message saying "No data available". I discovered th ...

Using a callback function with a function outside the scope in Angular 6

I am currently utilizing DevExtreme components, and here is where the callback function is invoked within the HTML: <dxi-validation-rule type="custom" [validationCallback]="validationCallback" message="Email exists"> </dxi-validation-ru ...

Guide to utilizing selenium for triggering Angular events (ng-click)

Attempting to invoke an angular ng-click through selenium is proving to be quite challenging. The focus lies on this particular snippet of javascript: <span class="col" ng-click="getHope(1,'pray','smile')">100%</span> This ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

What is the process for sending an HTTP post request with a React/Typescript frontend and a C#/.Net backend?

In the frontend code, there is a user login form that accepts the strings email and password. Using MobX State Management in the userstore, there is an action triggered when the user clicks the login button to submit the strings via HTTP post. @action logi ...

Embracing Angular2 - incorporating external modules

Attempting to incorporate the phoenix_js NPM module into my Angular2 app (which was created using the Angular2 CLI) is proving to be a challenge. I keep encountering the error message Cannot find module 'phoenix_js'. Many others have also faced t ...

Can you demonstrate how to showcase images stored in an object?

Is there a way to properly display an image from an object in React? I attempted to use the relative path, but it doesn't seem to be working as expected. Here is the output shown on the browser: ./images/avatars/image-maxblagun.png data.json " ...

What is the best way to send headers to the ngx-logger's post method for a server URL?

We are currently considering the use of ngx-logger in Angular 4 for server logging. However, we have encountered an issue with passing headers along with the serverLoggingUrl. BrowserModule, HttpModule, LoggerModule.forRoot( { serverLoggingUrl: &ap ...