Error: The payload in action is not able to be iterated over

Currently, I am delving into the world of ngrx, but I seem to have hit a roadblock. I'm encountering an issue that I can't seem to fix on my own. If anyone out there has some insight and expertise to offer, please help me out. I keep running into a TypeError: action.payload is not iterable error. When I modify [...action.payload] to just action.payload in reducer.ts, I get the data I need, however, I actually require the use of [...action.payload]. What could be causing this problem? Thank you.

images.reducer.ts

import { Image } from "../../../Image/models/image.model";

import * as ImagesActions from "./images.action";

export interface State {
  images: Image[];
}

const initialState: State = {
  images: [],
};

export function imagesReducer(
  state = initialState,
  action: ImagesActions.ImagesActions
) {
  switch (action.type) {
    case ImagesActions.GET_IMAGES:
      console.log(state.images);
      console.log("get images reducer ", action.payload);

      return {
        ...state,
        images: [...actin.payload],
      };
    default:
      return state;
  }
}

images.effect.ts

fetchImages$ = createEffect(
    () => {
      console.log("fetch images effect ");

      return this.actions$.pipe(
        ofType(ImagesActions.FETCH_IMAGES),
        map((action: ImagesActions.FetchImages) => action.payload),
        switchMap(() => {
          return this.http.post<Image[]>(this.globalUrl + "/admin/image");
        }),
        map((images) => {
          console.log(images);

          //return images.map((image) => {
          return {
            ...images,
            //images: image ? image : [],
          };
          //});
        }),
        map((images) => {
          console.log("fetch images effect images ", images);
          return new ImagesActions.GetImages(images);
        })
      );
    }
  );

images.action.ts


export class GetImages implements Action {
  readonly type = GET_IMAGES;
  constructor(public payload: Image[]) {}
}


app.reducer.ts

import { ActionReducerMap } from "@ngrx/store";

import * as fromUsers from "../admin/users/store/users.reducer";
import * as fromImages from "../admin/image/store/images.reducer";
import * as fromPosts from "../admin/post/store/posts.reducer";

export interface AppState {
  users: fromUsers.State;
  images: fromImages.State;
  posts: fromPosts.State;
}

export const appReducer: ActionReducerMap<AppState> = {
  users: fromUsers.usersReducer,
  images: fromImages.imagesReducer,
  posts: fromPosts.postsReducer,
};

Answer №1

When writing this code, keep in mind that you are creating an object rather than an array.

        switchMap(() => {
          return this.http.post<Image[]>(this.globalUrl + "/admin/image");
        }),
        map((images) => {
          return {
            ...images,
          };
        }),

To clarify, here is an example:

{ ...['a', 'b', 'c'] }
-->
{0: "a", 1: "b", 2: "c"}

Answer №2

Wrap the function you are invoking in an object like [{...action.payload}]

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

Ways to incorporate suspense with NextJS 14 - how can I do it?

I am looking to add a suspense effect to the initial loading of my page while the assets are being fetched. These assets include images on the home screen or as children of the RootLayout component. How can I implement an initial Loading state for these ...

The ES6 import feature conceals the TypeScript definition file

I currently have two definition files, foo.d.ts and bar.d.ts. // foo.d.ts interface IBaseInterface { // included stuff } // bar.d.ts interface IDerivedInterface extends IBaseInterface { // more additional stuff } Initially, everything was funct ...

Guide on displaying a tooltip for an object in an Angular component using Bootstrap syntax

i have a data object structured like this var obj = {"test price type ty dynamic ": 10, test: 7, pricetype1u: 0, Price type 3: 0, Price type 2: 0} in my Angular component HTML, with Bootstrap styles applied, I've written the following code ...

Standing alone, an argument can never be fully validated without

Recently, while delving into the valuable resource titled Effective TypeScript by Dan Vanderkam, I stumbled across an intriguing scenario that left me puzzled. Within a code snippet presented in the book, there was a line - shape; that seemed perplexing ...

Expanding a class in Typescript by adding a function with the same name but varying properties and types

class A { play(a: string): string{ return a; } } class B extends A { play(c: string, b: number): string{ return c + ' ' + b.toString(); } } let x = new A(); console.log(x.play('John')); let y = new B(); console.lo ...

Can Angular Material allow for unique CSS styling on each component?

As stated in the Angular Material Documentation, it is necessary to include the entire theme in order for the framework to function properly. This entails styles for all components. However, I am creating a component library and only pulling specific comp ...

Guide to building a nested dropdown navigation in Angular 12 with the power of Bootstrap 5

I am looking to implement a multilevel dropdown feature in my Angular 12 project with Bootstrap 5. Can someone please guide me on how to achieve this? For reference, you can view an example here. Thank you in advance! ...

Option in TypeScript to retain the '//' in the filename when removed

I'm currently attempting to implement the angular2 quick start example in my local environment. The only feasible way for me to serve the application is as a plugin within an existing application on my system. This particular application hosts a web ...

Use ngFor to filter content from another ngFor loop

I am in the process of creating a mobile application that involves filtering students based on their classes assigned by a teacher. Initially, I use ngFor to display all the classes taught by the teacher in a div, and then I aim to list the students enroll ...

Sharing variables between components within the same file in Angular 6

I have an Angular 6 application that relies on APIs to function. Within my app, I need to display certain data from the APIs in an Angular Material Dialog. The dialog Component is located alongside the main component used to showcase the API data. However ...

JavaScript - Assigning the same value to 2 properties but console log displays them as distinct values

While iterating through an array of documents, I am encountering a strange issue where setting two properties to the same value results in them having different values when logged using console.log. Here is the code snippet: this.logicItem.$promise.then( ...

Issue: The Karma plugin in Angular CLI >6.0 is now exported from "@angular-devkit/build-angular" instead

Issue: I'm encountering an error in Angular CLI version 6.0 or higher where the Karma plugin is now exported by "@angular-devkit/build-angular". // Below is the Karma configuration file, you can find more information at // module.exports = function ...

Angular failing to detect Leaflet TimeDimension

Recently, I integrated leaflet-timedimension into an Angular project that utilizes ngx-leaflet. However, I encountered a hurdle when trying to utilize the geoJson time dimension feature. It appears that Angular is not recognizing the leaflet-timedimension ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Error message in VsCode plugin stating that property 'X' is not found on type '{}' within a Vue 3 template

Currently, I am in the process of setting up my vue-cli project that utilizes the composition API with <script setup> to fully integrate TypeScript. Each time I try to use variables within template tags, VSCode flags errors. I have already installed ...

Exploring TypeScript's Classes and Generics

class Person { constructor(public name: string) {} } class Manager extends Person {} class Admin extends Person {} class School { constructor(public name: string) {} } function doOperation<T extends Person>(person: T): T { return person; } ...

Struggling with getting Angular 2 npm start to function properly, as it keeps returning Exit status

I am facing an issue with my angular 2 application on my laptop. It works fine for me, but when my teammate tries to clone it using git, he encounters a strange error when running npm start. He has node.js installed and the files are exactly the same. He ...

Using ngFor directive to iterate through nested objects in Angular

Receiving data from the server: { "12312412": { "id": "12312412", "something": { "54332": { "id": "54332", "nextNode": { "65474&q ...

Potential absence of the object has been detected after performing object verification

I encountered an issue with the following error message: Object is possibly 'undefined'.ts(2532) This is what my configuration looks like: export interface IDataColumns { name: string; label: string; display: string; empty: boolean; fi ...