NgRx State Reset to Null After Successful Authentication Action and Component Refresh

71 Views Asked by At

After a successful authentication action, the NgRx state is correctly updated with the authenticated user. However, upon refreshing the component or navigating, the data in the state appears to be reset to null.

user.action :

export const setUser = createAction('[User] Set User', props<{ user: User }>());

index.ts:

export const metaReducers: MetaReducer<AppState>[] = isDevMode() ? [] : [];

user.reducer:

export interface UserState {
    user: User | null;
  }

  export const initialState: UserState = {
    user: null,
  };

  export const userReducer = createReducer(
    initialState,
    on(UserActions.setUser, (state, { user }) => ({ ...state, user }))
  );

user.selector:

export const selectUserState = createFeatureSelector<UserState>('user');

export const selectUser = createSelector(
  selectUserState,
  (state) => state.user
);

app.state

import { UserState } from './reducers/user.reducer';

export interface AppState {
  user: UserState;
}

app.config:

export const appConfig: ApplicationConfig = {
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
    provideRouter(routes, withComponentInputBinding()),
    provideClientHydration(),
    provideHttpClient(withFetch(), withInterceptorsFromDi()),
    importProvidersFrom([
      HttpClientModule,
      TranslateModule.forRoot(provideTranslation()),
    ]),
    provideAnimations(),
    provideStore(reducers, { metaReducers }),
    provideStoreDevtools({ maxAge: 25, logOnly: !isDevMode() }),
  ],
};

I expected that, after a successful authentication, the NgRx state would retain the user data across component refresh or navigation. However, despite the correct dispatch of the setUser action, the data in the state appears to reset to null upon component refresh or navigation.

1

There are 1 best solutions below

0
On

NgRx only keeps state in memory (and thus loses its state on a refresh). If you want to persist state across reloads, you can use the local/session storage, e.g. with https://www.npmjs.com/package/ngrx-store-localstorage

the issue occurs not when refreshing the entire page (F5), but rather when navigating between components within the application without performing a full page refresh.

This shouldn't happen. But it's hard to say what's wrong without the whole picture/an example.

It seems like something is resetting the state, or the selector isn't wired up currectly.

I recommend to use the NgRx DevTools to see what's going on, and what's affecting the state.

Another thing that I can think of is that there's a full page reload while navigating, which is not intended.