The NgRx Store encountered an error: Unable to freeze

I am currently developing a basic login application using Angular, NgRx Store, and Firebase. I have implemented a login action that is supposed to log in to Firebase and store the credentials in the store. However, it seems like there is an issue in my implementation. After dispatching the action, the firebase request is successful, the credentials are returned, but the store does not update as expected. Instead, I encounter the following error in the console:

ERROR TypeError: Cannot freeze
    at Function.freeze (<anonymous>)
    at freeze (ngrx-store.js:843)
    at ngrx-store.js:857
    at Array.forEach (<anonymous>)
    at freeze (ngrx-store.js:845)
    at ngrx-store.js:857
    at Array.forEach (<anonymous>)
    at freeze (ngrx-store.js:845)
    at ngrx-store.js:857
    at Array.forEach (<anonymous>)

I am aware that the state is immutable and this error might be related to that, but I am struggling to identify the exact problem. Below is the code snippet I am working with:

State:

export interface CoreState {
  readonly credentials: UserCredential
}

export const initialCoreState: CoreState = {
  credentials: {} as UserCredential
}

Actions:

const signIn = createAction(
  `${actionPrefix} Sign In`,
  props<{ email: string, password: string }>()
);

const signInSuccess = createAction(
  `${actionPrefix} Sign In Success`,
  props<{ readonly userCredential: UserCredential }>()
);

const signInFailure = createAction(
  `${actionPrefix} Sign In Failure`,
  props<{ readonly error: string }>()
);

export const CoreActions = {
  signIn,
  signInSuccess,
  signInFailure
}

Effects:

@Injectable()
export class CoreEffects {
  signIn$ = createEffect(() =>
    this.actions$.pipe(
      ofType(CoreActions.signIn),
      switchMap(({ email, password }) =>
        this.authenticationService.signInWithEmailAndPassword(email, password)
          .pipe(
            map((userCredential: UserCredential) => {
                return CoreActions.signInSuccess({ userCredential })
              }
            ),
            catchError(error =>
              of(CoreActions.signInFailure({ error: error.statusText }))
            )
          )
      ),
    )
  );

  constructor(
    private readonly actions$: Actions,
    private readonly authenticationService: AuthenticationService
  ) {}
}

Reducer:

export const coreReducer = createReducer<CoreState>(
  initialCoreState,

  on(CoreActions.signInSuccess, (state, { userCredential }) => {
    console.log('Inside Reducer');
    return {
      ...state,
      credentials: userCredential
    }
  })

)

Upon further investigation, I discovered that by using Object.freeze(userCredentials) before passing it from effects to signInSucess, and then applying Object.freeze(userCredentials) again before assigning it in the reducer, it resolves the issue. However, this workaround feels unconventional to me. If anyone can provide insights or point out where I may be going wrong, I would greatly appreciate it. Thank you!

Edit: Added AuthenticationService and App Component

AuthenticationService

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  constructor(private readonly angularFireAuth: AngularFireAuth) { }

  signOut(): Observable<void> {
    return from(this.angularFireAuth.signOut());
  }

  createUserWithEmailAndPassword(email: string, password: string): Observable<UserCredential> {
    return from(this.angularFireAuth.createUserWithEmailAndPassword(email, password));
  }

  signInWithEmailAndPassword(email: string, password: string): Observable<UserCredential> {
    return from(this.angularFireAuth.signInWithEmailAndPassword(email, password));
  }
}

App Component

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'firebase-auth';

  constructor(private readonly store: Store) {}

  onClick(): void {
    const email = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3a4e5f494e7a4e5f494e14595557">[email protected]</a>';
    const password = '123456';
    this.store.dispatch(CoreActions.signIn({ email, password }))
  }
}

Answer â„–1

After reviewing the code you provided, everything appears to be in order. I suspect that the component or service is responsible for altering the state once it has been obtained through a selector.

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

The "export 'ɵɵcomponentHostSyntheticListener' (imported as 'i0') was not found in '@angular/core" error occurred during the Angular build

Trying to set up an Angular application with clarity UI. Using Angular version 10.1.1 and after adding clarity, encountering build errors. ERROR in ./node_modules/@clr/angular/esm2015/utils/animations/expandable-animation/expandable-animation.js 33:8-43 &q ...

Exploring type definition for function arguments in TypeScript and React

There is a high-order component (HOC) designed to store the value of one state for all input and select elements. The output function accepts arguments ({text: Component, select: Component}). An error is displayed while typing an argument: TS2322: Type &ap ...

Once the data being interpolated undergoes a change, implement a setTimeout function in Angular 7

To hide the element with a specific value when displayed I attempted to monitor the incoming message (which changes from an old value to a new one) and added a timeout to the new message. However, there is a delay between the message arriving and appearin ...

Creating a dynamic linear gradient background color using Angular 2 binding

Using static values works perfectly <div style="background: linear-gradient(to right, #0000FF 0%, #0000FF 50%, #FFA500 50%, #FFA500 100%);"></div> in my TypeScript file. this.blueColor = '#0000FF'; this.orangColor = '#FFA500&a ...

Dealing with client-side exceptions in a Next.js 13 application's directory error handling

After carefully following the provided instructions on error handling in the Routing: Error Handling documentation, I have successfully implemented both error.tsx and global-error.tsx components in nested routes as well as the root app directory. However, ...

Is your Typescript struggling to infer types correctly?

I created a function that converts an Array into a Map: function toMap<T,TKey,TElement>(items: Array<T>, keySelector: (item: T) => TKey, elementSelector: (item: T) => TElement ): Map<TKey,TElement> { var ma ...

Building a Dynamic Video Element in Next Js Using TypeScript

Is there a way to generate the video element in Next JS using TypeScript on-the-fly? When I attempt to create the video element with React.createElement('video'), it only returns a type of HTMLElement. However, I need it to be of type HTMLVideoEl ...

Creating dynamic and engaging videos using Angular with the ability to make multiple requests

I am facing an issue while working with videos in Angular. I am fetching the video URLs from an API to embed them in my application using the sanitazer.bypassSecurityTrustResourceUrl function provided by Angular. The videos are being displayed correctly wi ...

Oops! Looks like the serve command needs to be executed within an Angular project, however, the system could not locate a project definition

Currently, I am attempting to clone the git repository for Tour of Heroes with NgRX (blove/ngrx-tour-of-heros) Despite my efforts, I am encountering issues running the application. Even after updating my Angular CLI to version 7.3 and installing Yarn in ...

For each array element that is pushed, create and return an empty object

I am encountering an issue with an array where the objects are being generated by a push operation within a function. Despite successfully viewing the objects directly in the array, when I attempt to use forEach to count how many times each id uses the ser ...

JavaScript => Compare elements in an array based on their respective dates

I have an array consisting of more than 50 objects. This array is created by concatenating two arrays together. Each object in this array contains a 'date' key with the date string formatted as: `"2017-03-31T11:30:00.000Z"` Additionally, there ...

Designing a visual showcase with interactive tab links for image selection

I have been working on developing an Angular component that simulates a tab gallery functionality, inspired by this example. Below is my HTML structure: <div class="gallery-container"> <div class="display-container"> ...

Angular 2+ consecutive route parameters with the final one being without a component

Looking for a solution to add a third parameter to the existing route path structure section/sectionId/dashboardId: const appRoutes: Routes = [ { path: 'section/:sectionId', component: SectionComponent, children: [ { ...

The onChange event does not work as expected for Select controls

I am facing an issue with my common useForm.tsx file when handling the onChange event for select controls. The error message I encounter is displayed below. Does anyone have any suggestions on how to resolve this? Error: Type '(e: ChangeEvent<HTM ...

Display responsive input field based on selected option in ionic2 dropdown menu

When the user selects 'Other' from the dropdown menu using Ionic2 and Angular2, I want to provide them with an option to enter their profession. Here is a visual representation of the select box: Below is the code snippet for achieving this fun ...

retrieve a collection of objects using Angular CLI

Hey there, I'm currently working on fetching data using a get request in Angular. My Apartment class is structured as follows: export class Apartment { id: number; address: string; constructor(id: number, name: string) { this.id = id; ...

Determine whether an element is visible following a state update using React Testing Library in a Next.js application

I'm looking to test a NextJS component of mine, specifically a searchbar that includes a div which should only display if the "search" state is not empty. const SearchBar = () => { const [search, setSearch] = useState(""); const handleSear ...

Ensure that the objection model aligns with the TypeScript interface requirements

I am currently working on implementing an API using express, objection.js, and TypeScript. I found a lot of inspiration from this repository: https://github.com/HappyZombies/brackette-alpha/tree/master/server/src Similar to the creator, I aim to have var ...

The exportAs attribute is not specified as "ngForm" for any directive

Encountered an error while attempting to test the LoginComponent PhantomJS 2.1.1 (Linux 0.0.0): Executed 3 of 55 (1 FAILED) (0 secs / 0.307 secs) PhantomJS 2.1.1 (Linux 0.0.0) LoginComponent should create FAILED Failed: Uncaught (in promise): Error: Templ ...

What is the significance of the code statement in the Angular ng2-table package?

Could you please explain the functionality of this specific code line? this.rows = page && config.paging ? this.changePage(page, sortedData) : sortedData; ...