Search code examples
angularngrx

Retrieving a property from an action value in Angular 9 & NgRx reducer


I'm having trouble retrieving the property of a value in an NgRx reducer. I'm trying to extract the accessToken of the user object and store it in the state. However, despite the user object being valid and containing a valid accessToken, when I try to retrieve the accessToken it returns undefined.

In the debugger if I hover over the user object, I can see the full value with all the properties including accessToken, but if I skip to the next line and hover over accessToken object it shows undefined.

import { createReducer, on } from '@ngrx/store';
import { User } from 'src/app/models/user.model';
import { AuthActions } from '../action-types';

export const authFeatureKey = 'auth';

export interface AuthState {
  user: User;
  accessToken: string;
}

export const initialAuthState: AuthState = {
  user: undefined,
  accessToken: undefined,
};

const reducer = createReducer(
  initialAuthState,

  on(AuthActions.signup, (state, action) => {
    return {
      user: action.user,
      accessToken: action.user.accessToken,
    };
  }),

  on(AuthActions.signin, (state, action) => {
    // split out to debug.
    const user = <User>action.user; // action.user returns a valid object
    const token = user.accessToken; // despite this being valid in the user object, returns undefined.
    return {
      user: action.user,
      accessToken: token,
    };
  }),

  on(AuthActions.signOut, () => {
    return {
      user: undefined,
      accessToken: undefined,
    };
  }),
);

export function authReducer(state, action) {
  return reducer(state, action);
}

These are the actions:

import { createAction, props } from '@ngrx/store';
import { User } from '../../models/user.model';

export const signup = createAction('[SignUp Page] User SignUp', props<{ user: User }>());

export const signin = createAction('[SignIn Page] User SignIn', props<{ user: User }>());

export const signOut = createAction('[Top Menu] User SignOut');

and these are the selectors:

import { createFeatureSelector, createSelector } from '@ngrx/store';
import * as fromAuth from './reducers';

export const selectAuthState = createFeatureSelector<fromAuth.AuthState>(fromAuth.authFeatureKey);

export const isLoggedIn = createSelector(selectAuthState, (auth) => !!auth.user);

export const isLoggedOut = createSelector(isLoggedIn, (loggedIn) => !loggedIn);

export const getCurrentUser = createSelector(selectAuthState, (auth) => auth.user);

export const getAccessToken = createSelector(selectAuthState, (auth) => auth.accessToken);

This is the auth.module.ts, showing the import of the authReducer (as requested)

import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';

import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { AuthRoutingModule } from './auth-routing.module';
import { AuthService } from './services/auth.service';
import * as fromAuth from './store/reducers';
import { AuthEffects } from './store/auth-effects';

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    AuthRoutingModule,
    HttpClientModule,
    StoreModule.forFeature(fromAuth.authFeatureKey, fromAuth.authReducer),
    EffectsModule.forFeature([AuthEffects]),
  ],
  providers: [AuthService],
})
export class AuthModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AuthModule,
      providers: [AuthService],
    };
  }
}

I have noticed that in the state, it's storing the value somewhat weirdly:

auth
    user
      user
         userName: "username1"
         email: "email@email.com"
         accessToken: "ey......7z"
         refreshToken: "xxx"

So it looks like it's somehow nesting the user object.


Solution

  • This was my mistake, the service was passing the result back as a User object:

      signin(credentials: SignInCredentials): Observable<User> {
        return this.http.post<User>('/api/signin', credentials);
      }
    

    However, it was actually the user inside an object:

    {
       user: {
          userName:
          ...
       }
    }
    

    This is where it all went wrong. So I changed the service to return an any:

      signin(credentials: SignInCredentials): Observable<any> {
        return this.http.post<User>('/api/signin', credentials);
      }
    

    and changed the action dispatch:

    this.authService
      .signin(this.credentials)
      .pipe(
        tap((data: any) => {
          this.store.dispatch(AuthActions.signin({ user: data.user }));
          this.router.navigateByUrl('/');
        }),
    

    Feeling like an idiot.