Having trouble with setting up a Store with Ngrx in an Angular application

Could someone assist me in troubleshooting the error by analyzing the code provided below? I am new to Angular and unfamiliar with the Ngrx concept. You can also view a screenshot of the error here: https://i.sstatic.net/yhM0G.png

package.json

{
  "name": "recipe-book",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~12.1.1",
    // More dependencies listed...
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.1.1",
    // More devDependencies listed...
  }
}

app.reducer.ts

// Code snippet for app reducer...

recipes.action.ts

// Code snippet for recipes actions...

recipes.effects.ts

// Code snippet for recipes effects...

recipes.reducer.ts

// Code snippet for recipes reducer...

The error I encountered in app.reducer.ts is shown below:

// Error message regarding app.reducer.ts...

Answer №1

Your Reducer function should accept two values and return state. If you have decorated your app with ActionReducerMap<T>, then you should provide ActionReducer<> instead of a normal function.

Solution 1 To resolve this issue, simply remove ActionReducerMap<T> from your appReducer. Keep in mind that NgRx has changed the way to write state, action, effects, selectors, and reducers. The newer method involves using ActionReducerMap. You can read more about it here (Look at the second solution).

Solution 2 Update your NgRx state files by following the new method provided by NgRx:

recipes.actions.ts

import { createAction, props } from '@ngrx/store';
import { Recipe } from '../recipe/recipe.model';

let actionTypes = {
  FETCH_RECIPES : '[Recipes] Fetch Recipes',
  SET_RECIPES : '[Recipes] Set Recipes',
}

export const FetchRecipes = createAction(actionTypes.FETCH_RECIPES);
export const SetRecipes = createAction(actionTypes.SET_RECIPES,props<{recipe:Recipe[]}>());

recipes.effects.ts

//....imports , all the imports will come here
@Injectable()
export class RecipesEffects {
  constructor(private action$: Actions, private http: HttpClient) {}
  fetchRecipt$ = createEffect(() =>
    this.action$.pipe(
      ofType(FetchRecipes),
      mergeMap(action =>
        this.fetchFromUrl().pipe(map(result => SetRecipes({ recipe: result })))
      )
    )
  );

  fetchFromUrl() {
    return this.http.get<Recipe[]>(
      'https://recipebook-a7054-default-rtdb.firebaseio.com/recipes.json'
    );
  }
}

recipe.reducer.ts


import { createReducer, on,Action } from '@ngrx/store';
import * as RecipesActions from './recipes.actions'

export interface State {
  recipes: Recipe[];
}
const initialState: State = {
  recipes: [],
};

const reducer = createReducer(initialState,
  on(RecipesActions.SetRecipes,(state,payload)=>{
    return {...state,recipes:[...payload.recipe]}
  })
  )

  export function RecipesReducer (
    state = initialState,
    action: Action
  ) {
    return reducer(state,action)
  }
  

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

Using a comma as a decimal separator for input is not permitted when working with angular/typescript/html

I am facing an issue with my Angular frontend where I have numerous html input fields that trigger calculations upon typing. <input type="text" [(ngModel)]="myModel.myAttribute" (input)="calculate()"> The problem arise ...

Accessing data from an object of type Request in NodeJS using Typescript

Is there a way for me to retrieve req.kauth.grant It is definitely populated because when I print req, I see this: kauth: { grant: Grant { access_token: [Token], refresh_token: undefined, id_token: undefined, token_type: undefi ...

Is moduleId a reserved word in Angular2 / CLI?

After downloading the newest CLI version, I initiated a fresh test project. angular2 version: "^2.3.1" "@angular/compiler-cli": "^2.3.1", "typescript": "~2.0.3" Within AppComponent, there is this constructor: export class AppComponent ...

Transform angularjs directive into angular 10

After stumbling upon this intriguing code snippet, I decided to integrate it into my angular project: 'use strict'; /** * A mesmerizing floating text animation */ angular.module('g1b.text-animation', []). directive('textAnimatio ...

Can you provide guidance on defining functions using standard syntax and incorporating children in React with TypeScript?

There are multiple ways to type it, such as using the interface React.FC<YourInterface> or explicitly declaring in an interface the type of children as JSX.Element or React.Node. Currently, my approach is: const MyComponent: React.FC<MyInterface& ...

Issues with implementing Firebase Phone Authentication in Ionic 3

When trying to authenticate a phone number in Ionic 3 using Firebase, the program runs without error. However, after entering the phone number, nothing happens... The .html code is shown below: <ion-item> <ion-label stacked>Phone Number</i ...

Obtain map coordinates in Angular 10 using OpenLayers when a click event occurs

I'm facing an issue with my OpenLayers map embedded in an Angular map component. I am trying to retrieve the click coordinate of the map when the Angular (click) event is triggered. In JavaScript, it's straightforward by using the following code: ...

Utilizing Vue and TypeScript - Retrieving a Variable Declared in the Data() Method within Another Method

I recently made the switch to using Vue3 with TypeScript after previously working with Vue2 and JavaScript. I am encountering an issue in my IDE where it is showing an error (even though the code itself functions correctly, but may not be entirely accurate ...

The culprit behind Angular 11 app error: Unidentified router outlet triggering 'No routes match' issue

In my Angular 11 application, I am utilizing a named router-outlet. The setup in my app.component.html file looks like this: <ng-container *ngIf="showGeneric"> <router-outlet name="general"> </router-o ...

The error encountered is: "Unable to modify the 'x' property as it is readonly for the '[object Array]' object."

I've attempted various methods to modify this problem, regardless of how it's explained on different Stack Overflow threads. I am faced with an obstacle where I have an array composed of objects, and my goal is to iterate through the array and mo ...

The declaration file for module 'vue-tabulator' was nowhere to be found

Trying to incorporate the vue-tabulator Vue component from https://github.com/angeliski/vue-tabulator into a basic Vue application written in TypeScript. main.ts: import Vue from 'vue' import VueTabulator from 'vue-tabulator' import A ...

Cypress error: Unable to access 'uid' property as it is undefined

Recently in my Cypress project with TypeScript support utilizing the Cucumber Preprocessor, an unexpected exception has started appearing: TypeError: Cannot read properties of undefined (reading 'uid') There are instances where changing to a di ...

Solving CORS policy error in a MEAN stack application deployed on Heroku

I've been grappling with a CORS policy error in my MEAN stack app for quite some time now. The specific error message I keep encountering is: "Access to XMLHTTPRequest at <my heroku app url.com/login> from origin has been blocked by CORS ...

Having trouble with the sx selector not functioning properly with the Material UI DateTimePicker component

I'm currently working with a DateTimePicker component and I want to customize the color of all the days in the calendar to match the theme color: <DateTimePicker sx={{ "input": { color: "primary.main&quo ...

Define the data type of the array within hooks, then proceed with initialization

After attempting to populate the state using data fetched by RNFS.readDir, I encountered an issue where the state was being reinitialized. interface fileUnit { type: string, index: number, title: string, path: string, date: string, size: numbe ...

Using optional chaining along with the methods toLowerCase and indexOf while iterating through an array using the map

I have implemented an autocomplete input that searches for project properties while typing. I am looking to enhance the existing code for better performance. filterProjects(value: string) { return this.projects.filter( project => project.key ...

Updates to TypeScript 2.3.1 creating disruptions in SystemJS plunk

Check out this official Angular + TypeScript plunk using SystemJS 0.19.31, now updated to TypeScript 2.3.0. However, changing the SystemJS configuration in the same plunk to TypeScript 2.3.1 or 2.3.2 'typescript': 'npm:<a href="/cdn-cgi ...

Troubleshooting Problem with Uploading Several Photos to Firebase Storage

I need assistance with uploading multiple photos to Firebase Storage. Despite my efforts, it seems that the original upload keeps getting overwritten and the folder with the venueID property is not being created. Can someone provide some guidance on this i ...

Encountering a "Multiple registrations of the method 'get' on the path '../api/' error" with Swagger

I am utilizing OpenAPI / Swagger in an Angular application built on .NET Core, and I am facing the error "The method 'get' on path '../api/' is registered multiple times" while generating frontend TypeScript code using NSwag Studio. Fro ...

Connect ngModel value between multiple components

If you have a file named about.component.ts, it would contain the following code: import { Component } from '@angular/core'; @Component({ selector: 'about-section', template: ` <input [(ngModel)]="name" placeholder="First N ...