0

I'm trying to implement authentication using ngrx with entity. My solution up to this point was to divide the users in the store so there is 'users' and 'user', the latter is used to track the authenticated user.

Id like to be able to display the logged in user data in the UI, which requires that I select the sole entity from 'user' store slice. However, I don't have a neat way of getting the id of the logged in user (since using entity adapter, things returned from the reducer must be stored as a key value pair)

question: Is there a way to get a singleton object out of entity, without the associated id? and is this implementation defeating the purpose of entity? I'm not tied to it, just wanted to stay in entity because the rest of the app uses it.

What I have now does not throw an error, but it also does not work:

//in app.component
user$ : Observable<User>;
    

    constructor(private store : Store<AppState>) {}

    ngOnInit() {
        // selectAll is the default selector from entity adapter
        this.user$ = this.store.select(fromUser.selectAll)[0];
        // selectAll returns an array, so 
        this.store.dispatch( userActions.getUser());
    }


I also wrote a custom selector which does essentially the same thing:

export const selectAuthenticatedUser = () =>
    createSelector(
        fromUser.selectAll,
        (entities : User []) => {       
            return entities[0]
        } 
    )

and I've experimented with using the rxjs.take method, but this causes bugs

export const selectAuthenticatedUser = () =>
    createSelector(
        fromUser.selectAll,
        (entities : User []) => {   
            return entities.take(1) 
        } 
    )
breadman0
  • 163
  • 1
  • 4
  • 14

1 Answers1

0

Perhaps I'm reading the question wrong, but if you're just storing a single entity in the state, I would recommend to not use @ngrx/entity and to just have a single "user" property.

If you decide to use @ngrx/entity and you just want to retrieve the stored item, your code snippet seems fine, but you can just assign the selector to a variable (instead of creating a factory method)

export const selectAuthenticatedUser = createSelector(
        fromUser.selectAll,
        (entities : User []) => {       
            return entities[0]
        } 
    )
timdeschryver
  • 14,415
  • 1
  • 19
  • 32