In Angular ngrx, when using parameters 'action' and 'action', it is important to note that they are not compatible with each other. Additionally, it is crucial that the property 'payload' is not

I have recently started working with Angular and I am using ngrx to manage the state in my application. However, when I try to compile the code, I encounter an error that says 'Types of parameters 'action' and 'action' are incompatible'. Can someone help me understand why this error is occurring and how can I resolve it?

 
    Error: src/app/shopping-list/store/shoppingList.actions.ts:9:5 - error TS2564: Property 'payload' has no initializer and is not definitely assigned in the constructor.
    
    9     payload: Ingredient;
          ~~~~~~~
    src/app/app.module.ts:25:27 - error TS2322: Type '(state: { ingredients: Ingredient[]; } | undefined, action: AddIngredient) => { ingredients: Ingredient[]; }' is not assignable to type 'ActionReducer<{ ingredients: Ingredient[]; }, Action>'.
      Types of parameters 'action' and 'action' are incompatible.
        Property 'payload' is missing in type 'Action' but required in type 'AddIngredient'.
    
    25     StoreModule.forRoot({ shoppingList: shoppingListReducer }),
                                 ~~~~~~~~~~~~
    
      src/app/shopping-list/store/shoppingList.actions.ts:9:5
        9     payload: Ingredient;
              ~~~~~~~
        'payload' is declared here.

This is the content of my shoppingList.actions.ts file.

import { Action } from '@ngrx/store'

import { Ingredient } from '../../shared/ingredient.model';

export const ADD_INGREDIENT = 'ADD_INGREDIENT';

export class AddIngredient implements Action {
    readonly type = ADD_INGREDIENT;
    payload: Ingredient;
}

And here is the shoppingList.reducer.ts file.


import { Ingredient } from "src/app/shared/ingredient.model";

import * as shoppingListActions from './shoppingList.actions';

const intialState = {
   ingredients: [
        new Ingredient("Apples", 3),
        new Ingredient("Tomatoes", 4)
    ]
}

export function shoppingListReducer(state = intialState, action: shoppingListActions.AddIngredient) {
    switch (action.type) {
        case shoppingListActions.ADD_INGREDIENT:
            return {
                ...state,
                ingredients: [...state.ingredients, action.payload]
            }
        default:
            return state;
    }
}

Finally, this is the content of my app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRouting } from './app-routing.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { StoreModule } from '@ngrx/store';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { SharedModule } from './shared/shared.module';
import { CoreModule } from './core.module';
import { shoppingListReducer } from './shopping-list/store/shoppingLis.reducer';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,

  ],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    StoreModule.forRoot({ shoppingList: shoppingListReducer }),
    AppRouting,
    SharedModule,
    CoreModule,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Answer â„–1

The reason for your issue is due to a problem with the signature,

When calling StoreModule.forRoot<unknown, Action>(reducers: ActionReducerMap<unknown, Action>)

While technically you are passing the correct parameter, there seems to be an error indicating that your Action object parameter contains a field named payload which is not present in the Action parameter of ActionReducerMap<unknown, Action>. Despite having already inherited Action in your action class:

class AddIngredient implements Action{

It's evident that the Action in ActionReducerMap<unknown, Action> is different than what is expected in '@ngrx/store', hence causing the compilation error.

To resolve this issue, you must make the following modifications:-

Firstly, create your State as shown below in your shopping-list.reducer.ts:

export interface ShoppingListState{
    ingredients: Ingredient[];
}

const initialState: ShoppingListState = {
    ingredients: [
        new Ingredient('Apples', 5),
        new Ingredient("Tomatoes", 4),
    ]
};

Additionally, update your reducer method like so:

export function shoppingListReducer(state: ShoppingListState = initialState, 
    action: shoppingListActions.AddIngredient): ShoppingListState {
    switch(action.type){

Next, create a file named index.ts (can have a different name) within the action folder at the same location as the reducer file:

import { ShoppingListState,  shoppingListReducer } from './shopping-list.reducer';
import { ActionReducerMap } from '@ngrx/store';


export const rootReducer = {};

export interface AppState {
    shoppingList: ShoppingListState;
};


export const reducers: ActionReducerMap<AppState, any> = {
    shoppingList: shoppingListReducer
};

Import these reducers into your app.module.ts:

import { reducers } from './reducers/'

Update your code as follows:

StoreModule.forRoot(reducers)

Also, it's recommended to avoid declaring variables like:

payload: Ingredient;

Instead, utilize constructors and modify your code accordingly:

export class AddIngredient implements Action {
    readonly type = ADD_INGREDIENT;
    constructor(public payload: Ingredient){}
}

These adjustments should help resolve your issue.

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

Testing VueJs components with Jest and Typescript: when the components are not mounted

Our team is in the process of developing an application using VueJs. Drawing from our past experience with Angular unit testing utilizing Jasmine and Karma, we have opted to implement Typescript for this VueJs project. Currently, I have created simple spe ...

Utilizing Datalist with dynamic JSON data in Angular 8: A comprehensive guide

I have a dynamic json feeding options into a datalist. The options also include a value attribute that appears in the dropdown selection list. How can I remove this value from the selection? Any help is appreciated. Here's the code snippet: home.comp ...

Angular2 tubes sieve through hyperlinks within HTML content

As I receive HTML strings from an external source, my goal is to filter out all links that contain images, remove the href attribute, and replace it with a click event. I have attempted to achieve this using an Angular pipe, but so far I have only been suc ...

What steps should I take to enable a route guard to authenticate a token once it has been stored in local storage?

I'm currently working on a basic login page with authentication using Angular and Express. Here's what I've got so far: a login component a service that handles http requests and stores the jwt token in local storage a route guard for the ...

Newest Angular package.json

Each time I attempt to update my Angular components to the latest version, I encounter the same error. It seems like a never-ending cycle... npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/ ...

Issue encountered while generating a fresh migration in TypeORM with NestJs utilizing Typescript

I am currently working on a Node application using TypeScript and I am attempting to create a new migration following the instructions provided by TypeORM. Initially, I installed the CLI, configured my connection options as outlined here. However, when I ...

Converting JSON data to an XML file and saving it to a designated directory using Angular

Currently in the process of implementing an XML Export feature, designed to transfer JSON data from a database into XML format and then save it as a .xml file within a specific directory. After attempting to follow this guide I encountered issues with n ...

The parent component's state does not reflect updates made by the child component's successful dispatch of a reducer through Redux Toolkit

I encountered a strange issue where the state slice is behaving correctly (verified by unit tests and manual testing). However, it appears that the react selector is not properly subscribing to it. Here is the parent component code: import { useSelector } ...

Vue 3 - Child Component Script Not Updating with Reactive Prop Changes

I am facing an issue where I am trying to pass a reactive data as a prop to a child component in Vue 3. The data updates correctly in the child component's template, but it does not reflect in the child component's script. In the parent component ...

Error Encountered | Invalid Operation: Unable to access attributes of undefined (referencing 'CodeMirror')

Error image on chrome Using Next.js 13 Encountering an error on Google Chrome, seeking a solution to fix it or possibly just ignore it. Not utilizing Codemirror and prefer not to use it either. Tried troubleshooting methods: Deleting ".next","node_ ...

Ways to ensure TypeScript shows an error when trying to access an array index

interface ApiResponse{ data: Student[]; } interface Student { name: string; } Imagine a scenario where we receive an API response, and I am confident that it will contain the data field. However, there is a possibility that the data could be an empty ...

Angular resolver does not return anything if the outcome is an observable generated using the .asObservable() method

While working on my project, I wanted to simulate my http calls by using a BehaviorSubject along with Observable properties in my resolver service. However, I faced an issue and I am not sure why this code snippet is not functioning as expected: schedule- ...

Incorporate New Element into the Express Request Object

I am attempting to enhance the Express request object by adding a property called "forwardingUrl". To achieve this, I utilized declaration merging in a file named ./typing.d.ts: declare namespace Express { export interface Request { forwardingUrl: ...

Array filtering using one array condition and additional boolean conditions

Sorting through the carArray based on user-specified conditions. If a user selects the red checkbox, only cars with red paint will be displayed. If a user selects the green checkbox, only cars with green paint will be displayed. If both the red and green ...

Having trouble getting my specialized pipe (filter) to function properly in Angular 2

I have implemented a custom pipe for filtering data in my table. Oddly, when I enter a search string into the input box, it correctly prints 'found' in the console but no rows are displayed in the table. However, if I remove the pipe altogether, ...

The feature of declaration merging does not function properly with the express 4.17.* request type

Looking to enhance the Request type, I decided to create a folder @types/express. Within this folder, I included a file index.d.ts with the following content. namespace Express { interface Request { user: number; } } Upon referencing req.user in V ...

Retrieve JSON data from a 404 response using the Http.get() method

I am attempting to retrieve JSON from a 404 response, but I am only receiving the Response {_body: "{myJSON}", status: 404, ok: false, statusText: "Not Found", headers: Headers…} How can I access the object itself so that I can display it in my HTML u ...

Issue with sending props to TypeScript React component

Having a challenge with styling a simple button component using styled components. When trying to send a prop to the component, TypeScript throws an error saying "No overload matches this call". App.tsx import React from 'react'; import Button ...

Facing a Bad Request error while trying to submit a Django Rest Framework Post request that appears to be valid, but is requiring a

Currently, I am in the process of creating a new instance of the SearchNeighborhood object and establishing a connection with an already existing SearchCity object through a POST request. The models I have set up are as follows: class SearchCity(models.M ...

Troubleshooting the issue of conditional extension in Typescript for "Array or Object" not functioning as anticipated

My goal is to create a TypeScript type generic that has the following structure: type APIDataShape<T extends { id: unknown } | Array<{ id: unknown }>> = T extends Array<any> ? Array<{ id: T[number]["id"]; ...