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

ag-grid-angular failing to present information in a table layout

I have implemented ag-grid-angular to showcase data in a structured table format, but the information appears jumbled up in one column. The data for my ag-grid is sourced directly from the raw dataset. https://i.stack.imgur.com/sjtv5.png Below is my com ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: Whenever an option is selected from the dropdown, it cl ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...

Create an interactive slider using only images in an Ionic Angular content display

I need help transforming the images from WordPress into a slider instead of showing them individually. How can I achieve this? <ion-content padding> <div *ngIf="selectedItem" class="selection"> <h2 [innerHTML]="selectedItem.title.rend ...

Strategies for addressing the issue of assigning "xx" to intrinsic attributes and props in React with TypeScript

I'm facing an issue where I am unable to locate 'count' and assign {count: number; title:string} type to IntrinsicAttributes in a React and TypeScript environment. There are two components involved, ParentComponent and ChildComponent. In t ...

Ensuring that all observables within a for loop have completed before moving on to the next block of code

Here is a scenario where the following code snippet is used: getPersons().subscribe( persons => { for (const person of persons) { getAddress(person.id).subscribe( address => { person.addres ...

Handling Concurrent HTTP Requests in Angular using RxJS (Independently Triggered)

Angular 6: Implementing Angular Multiple HTTP Requests with RxJS (for updatePhone and updateAddress) that are independent of each other but may or may not occur simultaneously. Scenario 1: When changes are made to address fields (such as address, state, c ...

Choosing and Duplicating Text in Angular

I'm attempting to give the user the ability to select a paragraph and copy it by clicking a button. However, my current code is not working as expected. I initially tried importing directives but encountered errors, prompting me to try a different met ...

Is there a way to transfer data to a different component in React without relying on a hierarchical parent-child relationship?

I am struggling to pass the data from the "SearchingData" Component to the "Search" Component. The SearchingData component is a child of the Search component. I need to transfer the data from the variable named "datacame" to the Search Component. Can som ...

Unexpected results observed in enumerators within typescript

Could someone clarify the results that I am seeing from the code below? enum days { sun = 1, mon = 0, tues }; console.log(days[1]); // outputs tues // should output -- mon console.log(days[0]); // outputs mon // should output -- sun Furthermore, how ...

Tips for resolving aliases in tsconfig.app.json when dealing with multiple source directories in WebStorm

When it comes to generating source files, I do things a bit differently and create some of them outside of the usual src directory. Here's how my structure looks: - project - generated - $ui-services some-other.service.ts - src - ...

Interface of TypeScript Undetermined

Currently, I am developing a Demo API Wrapper specifically for Roblox. During the development process, I have come across a certain issue that I would like to address. My aim is to send a request and then return all the data in the manner of an API wrapper ...

Tips for arranging TypeScript AST nodes and generating a TypeScript file as the final result

My objective is to reorganize the code in a way that sorts the link(foo) value based on the string text: import Text from '~/text.js' export default function rule(text: Text) { // Sorting rules alphabetically } Although I have made some progr ...

Limit access to a specific route within the URL

Is there a way to ensure that users can access and download myfile.pdf without being able to see or access /root, /folder, or /subdirectory in the URL? This functionality can be implemented using HTML, Angular 6, ReactJS, or similar frameworks. ...

Ways to effectively utilize an interface incorporating props.children and other property varieties

Currently working on a project with Next.js and Typescript. In order to create a layout component, I defined the following interface: export interface AuxProps { children: React.ReactNode; pageTitle: 'string'; } The layout component code sn ...

Utilize Hardhat and NPM to distinguish between unit tests and integration tests efficiently

Struggling with setting up two commands in my package.json for running unit tests and integration tests. I am having trouble defining the location of the testset for each type of testing. Within the scripts section of my package.json, I have created two c ...

Can one bring in a JavaScript function using webpack?

I have a unique JS library called: say-my-greeting.js function SayMyGreeting (greeting) { alert(greeting); } Now I want to incorporate this function in another (.ts) file; special-class.ts import SayMyGreeting from './say-my-greeting.js' ex ...

Using TypeScript to define values with the placeholder "%s" while inputting an object as a parameter

One common way to decorate strings is by using placeholders: let name = "Bob"; console.log("Hello, %s.", name) // => Outputs: "Hello, Bob." I'm curious if there's a way to access specific values within an object being passed in without specif ...

Enable users to designate custom methods as either asynchronous or synchronous

These are my TypeScript method signatures: onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; async onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; onPinnedUnhandledRejection?(info: HavenInfo, ...

ngModelChange doesn't trigger if the value is manually altered

Here is the scenario I am experiencing: //html <input (ngModelChange)="onSelection()" [(ngModel)]="selectedNode" > // in the ts file onSelection() { alert('changed'); } Typing something inside the input tri ...