The function type '(state: State, action: AuthActionsUnion) => State' cannot be assigned to the argument

I have encountered a persistent error in my main.module.ts. The code snippet triggering the error is as follows:

@NgModule({
  declarations: [
    PressComponent,
    LegalComponent,
    InviteComponent
  ],
  providers: [
    AuthService
  ],
  imports: [
    HomeModule,
    MainRoutingModule,
    ContactModule,
    EffectsModule.forRoot([
      AuthEffects
    ]),
    StoreModule.forRoot(AuthReducer, {
      metaReducers,
      runtimeChecks: {
        strictActionImmutability: true,
        strictStateImmutability: true,
      },
    }),
    SectionHeaderGroupModule,
    FormRegisterModule,
    ReactiveFormsModule
  ]
})

export class MainModule {
}

The specific error message that I am encountering reads:

Error:(34, 25) TS2345: Argument of type '(state: State, action: AuthActionsUnion) => State' is not assignable to parameter of type 'ActionReducerMap<State, Action> | InjectionToken<ActionReducerMap<State, Action>>'.
  Type '(state: State, action: AuthActionsUnion) => State' is not assignable to type 'InjectionToken<ActionReducerMap<State, Action>>'.
    Property '_desc' is missing in type '(state: State, action: AuthActionsUnion) => State'.

In an effort to resolve this issue, you can refer to my auth.reducer.ts file for context:

import { IUser } from '../shared/models/user';
import * as AuthActions from './auth.actions';

export interface State {
  user: IUser | null;
  error: any;
}

const initialState: State = {
  user: null,
  error: '',
};

export function AuthReducer(state = initialState, action: AuthActions.AuthActionsUnion): State {
  switch (action.type) {
    case AuthActions.AuthActionsTypes.GetUserDataGoogleSignIn: {
      return {
        ...state,
        user: action.payload,
        error: '',
      };
    }
    
    // Other cases omitted for brevity
    
  }
}

function getErrorMessage(error): string {
  switch (error) {
    case 'auth/wrong-password':
      return 'Wrong password';
    case 'auth/user-not-found':
      return 'IUser does not exist';
    case 'auth/invalid-email':
      return 'Invalid email address';
    default:
      return error;
  }
}

If you have any insights or solutions on how to rectify this error, kindly share them with me.

Answer №1

Your confusion between the syntax of ngrx v8 and v7 has been noted. Here is how I configure my code:

In app.module.ts

StoreModule.forRoot(ROOT_REDUCERS, {
  metaReducers,
  runtimeChecks: {
    strictStateImmutability: true,
    strictActionImmutability: true
  }
}),

Next, the root reducer:

import {
  ActionReducer,
  ActionReducerMap,
  MetaReducer,
  Action
} from "@ngrx/store";
import { environment } from "../../../environments/environment";
import * as fromRouter from "@ngrx/router-store";
import { InjectionToken } from "@angular/core";

/**
 * Every reducer module's default export is the reducer function itself. In
 * addition, each module should export a type or interface that describes
 * the state of the reducer plus any selector functions. The `* as`
 * notation packages up all of the exports into a single object.
 */
/**
 * As mentioned, we treat each reducer like a table in a database. This means
 * our top level state interface is just a map of keys to inner state types.
 */
export interface State {
  router: fromRouter.RouterReducerState<any>;
}

/**
 * Our state is composed of a map of action reducer functions.
 * These reducer functions are called with each dispatched action
 * and the current or initial state and return a new immutable state.
 */
export const ROOT_REDUCERS = new InjectionToken<
  ActionReducerMap<State, Action>
>("Root reducers token", {
  factory: () => ({
    router: fromRouter.routerReducer
  })
});

And here is how ngrx v8 writes the reducer:

import { createReducer, on } from "@ngrx/store";
import {
  EntityState,
  EntityAdapter,
  createEntityAdapter
} from "@ngrx/entity";

import * as PostActions from "../actions/post.actions";

import { IPost } from "../models/post.model";

export interface PostState extends EntityState<IPost> {
  selectedPost: IPost;
  errors: any;
}

const postAdapter: EntityAdapter<IPost> = createEntityAdapter<IPost>();

const initialState: PostState = postAdapter.getInitialState({
  selectedPost: null,
  errors: null
});

export const postReducer = createReducer(
  initialState,
  on(PostActions.LoadPostsSuccess, (state, { posts }) =>
    postAdapter.addAll(posts, state)
  ),
  on(PostActions.LoadPostSuccess, (state, { post }) => {
    return postAdapter.addOne(post, { ...state, selectedPost: post });
  }),
  on(PostActions.UpdatePost, (state, { post }) => {
    return postAdapter.updateOne(post, state);
    //return postAdapter.updateOne(post, { ...state, selectedPost: post });
  }),
  on(PostActions.UpdateSelectedPost, (state, { selectedPost }) => {
    console.log(selectedPost);
    return { ...state, selectedPost };
  }),

  //catch errors
  on(
    PostActions.LoadPostsFail,
    PostActions.LoadPostFail,
    PostActions.UpdatePostFail,
    (state, { errors }) => {
      return { ...state, errors };
    }
  )
);

export const { selectAll } = postAdapter.getSelectors();

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 installation process was unsuccessful due to an error in the postinstall script for [email protected]

While attempting to run npm install, an error message is displayed: Failed at the <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e38d8c8786ce90829090a3d7cdd6cdd3">[email protected]</a> postinstall script. I hav ...

CRUD operation: The DELETE method is invoked prior to the user's request

Upon opening the localhost:4200 app, I noticed an old delete request already present. Even when I try to use the new delete request by clicking the button, it gives me a 404 (Not Found) error. However, manually entering the URL into the search bar does del ...

Apologies, we are experiencing a server error. TypeError: Unable to access the 'map' property of an undefined

I'm struggling to grasp the concept of fetching external data using server-side rendering with the getServerSideProps method. In particular, I am facing difficulties with the search functionality and how to handle the returned data. As someone who is ...

Can you explain the purpose of this script? Is it considered harmful?

Today, I received a suspicious phishing email containing the following JavaScript code: <script type="text/javascript" language="Javascript1.1"> <!-- Begin var bCancel = false; function validateRegistrationDetails(form) { hm ...

When using React and React Router v6, make sure to implement a 404 status code response for unmatched routes

When it comes to managing unmatched routes with React Router, I have a solid understanding: <Routes> {/* Public routes */} <Route exact path="/" element={<Home />} /> // Other routes... {/* Error routes */} ...

How do you write functions in ES6?

When attempting to access my namespaced store in Vue, I encountered an issue: methods: { ...mapActions('Modal', [ 'toggleActive', ]), close: () => { this.toggleActive(); } This resulted in the follow ...

Using JavaScript to define an array of objects

My issue lies with transforming a JSON structure like the one below: [{ "groupid": 29, "percentage": 14 }, { "groupid": 29, "percentage": 22 }, { "groupid": 59, "percentage": 66, }] I am looking to convert it into the format shown ...

Iterate through an object, with certain keys being duplicated

Currently, I am facing a scenario where the object I'm analyzing is quite messy... Essentially, within this object... my goal is to locate the pageviews node, but only if it has an array of data... Here's an example of the data: data = [ ...

The type '{}' cannot be assigned to the type '{ title: string; text: string; }'

Upon executing the TypeScript code below, I encountered the following error: Type '{}' is not assignable to type '{ title: string; text: string; }'. Property 'title' is missing in type '{}'. The "article" declara ...

Effective ways to request verification prior to eliminating an item with ng-select (multi-select)

https://i.stack.imgur.com/HDtXq.jpg Is it possible to add a confirmation prompt when deleting an item from a select component? I couldn't find any specific prop for the component. Is there any way to customize or override the delete function? ...

Transform a dropdown menu into an inverted footer

I stumbled upon a unique dropdown menu design that I want to tweak and reverse, making it an innovative "dropup" menu that opens from the bottom to the top. Currently, this is what I have: HTML <div class="get-started"> <a href="#" id="get-s ...

Dynamically loading Ember templates with asynchronous requests

I need a way to dynamically load HTML content from another file using the code below: App.MainView = Ember.View.extend({ template:function(){ $.ajax({ url: 'views/main.html', dataType: 'text', async: false, ...

Ways of transferring session variables from one page to another?

Initially, I am working with multiple webpages in express. After saving a variable into a session during a post request, the page redirects to another page. However, when trying to access the variable on that new page, it is returned as "Undefined." Upon f ...

Angular, a Self-sufficient Module of Cascading Style Sheets

I have developed a factory that generates HTML content. I want to showcase this generated HTML within a specific section of my application, without its CSS affecting the rest of the site, and vice versa. While using an iframe is one option, I believe there ...

Using Angular 2, how to filter a single column based on multiple values?

If I have an array of objects as shown below [ {name: 'aaa', type: 'A'}, {name: 'bbb', type: 'B'}, {name: 'ccc', type: 'A'} .... ] I want to build a filter in Angular that displays ...

Adding up the values of an array based on their position in Javascript

I came across a JavaScript array that looks like this: var array1 = [ [1, 2, 3], [7, 9, 2], [6, 8, 1] ] What I'm aiming for is to get the following output: var array2 = [ 14, 19, 6 ] array1[0] = 1 + 7 + 6 array1[1] = 2 + 9 + 8 array1[2] = 3 + 2 + ...

Is there a way to utilize the 'interval' Rxjs function without triggering the Change Detection routine?

My goal is to display the live server time in my application. To achieve this, I created a component that utilizes the RXJS 'interval' function to update the time every second. However, this approach triggers the Change Detection routine every se ...

Divergence in results: discrepancy found in the outputs of nodejs crypto module and tweetnacl.js

Consider this code snippet in nodejs: import crypto from 'crypto'; const pkey = `-----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIJC52rh4PVHgA/4p20mFhiaQ/iKtmr/XJWMtqAmdTaFw -----END PRIVATE KEY-----`; // placeholder key function sign_message(m ...

Setting up only two input fields side by side in an Angular Form

I'm fairly new to Angular development and currently working on creating a registration form. I need the form to have two columns in a row, with fields like Firstname and Lastname in one row, followed by Phone, Email, Password, and Confirm Password in ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...