Trouble resolving user names from a separate state in Angular project with ngrx

23 Views Asked by At

I'm working on an Angular project using ngrx, where I have two states—one for users and another for projects. In the project state, each project has an Author and an Editor. The user state contains users as a Key-Value object, with only the keys fetched from the backend. I already have user data loaded in another state.

I am trying to use the user state to resolve the names of users in the project reducer, but my current implementation is not working. Here's the code:

In the User Selector:

export const getUserNameByIdSelector = (ids: number) => createSelector(
selectPeople, (state: PeopleState) => state.users.find(user => ids === user.Id).Name);

In the Project Reducer:

case ActionTypes.LoadAllProjectsSuccess: {
let projects = action.payload;
projects.map(p => ({
    ...p,
    Author: { ...p.Author, Value: getUserNameByIdSelector(p.Author.Key as number) },
    Editor: { ...p.Editor, Value: getUserNameByIdSelector(p.Editor.Key as number) }
}));
return {
    ...state,
    projects: projects
};}

I'm facing issues with this code, and the names are not being resolved correctly. Any ideas on how to fix this?

1

There are 1 best solutions below

0
Geo242 On

You main issue is that you are calling getUserNameByIdSelector directly without passing it as an argument into the store select function. You won't get the value you expect because the return type of getUserNameByIdSelector is MemoizedSelector, not the value.

That being said, there really is no good way that I know of to call a selector within a reducer. I would call that an anti-pattern.

What you might be able to do is to call your action with the data you need from within an effect, but that seems a bit hacky to me as well.

Or, you might want to think about refactoring your states so that you have all the data that relates to one another in a single slice of state.