Utilize NgRx's dispatch method to pass a payload and update the store

Exploring the world of ngRx is a new journey for me. I am currently in the process of establishing a store that will receive updates triggered by actions from components. NgRx create methods are being utilized to craft actions and reducers for this purpose.

request.Component.ts

import { Component } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Request } from '../models/request.model';
import { RequestState } from '../reducers/request.reducer';
import { Observable } from 'rxjs';
import { UpdateRequest , LoadAllRequests, DeleteRequest } from '../actions/request.actions';

@Component({
  selector: 'app-request',
  templateUrl: './request.component.html',
  styleUrls: ['./request.component.css'],
})

export class RequestComponent {
  request$: Observable<RequestState>;
  requestList =  Request[2] = [
    { RequestId : '1', Name : 'Test1'},
    { RequestId : '2', Name : 'Test2'},
    { RequestId : '3', Name : 'Test3'}
  ];

  constructor(private store: Store<{ request: RequestState }>) {
    this.request$ = store.pipe(select('request'));
  }

  UpdateRequest() {
    this.store.dispatch(UpdateRequest({request : this.requestList[0]}));
  }

  LoadRequests() {
    this.store.dispatch(LoadAllRequests({requestCollection: this.requestList}));
  }

  DeleteRequest() {
    this.store.dispatch(DeleteRequest({requestID : this.requestList[0].RequestId}));
  }
}

request.reducer.ts

import { UpdateRequest , LoadAllRequests, DeleteRequest } from '../actions/request.actions';
import { Request, RequestInitial } from '../models/request.model';
import {createReducer, on} from '@ngrx/store';
import { Action } from 'rxjs/internal/scheduler/Action';

// New Interface for Request State
export interface RequestState {
    requestCollection: Request[];
    request: Request;
    requestId: Request['RequestId'];
}

// Initialize Store State with Request Initial Const and empty values
export const requestInitialState: RequestState = {
    requestCollection: [],
    // requestCollection: Request[2] = [
    //   { RequestId : '1', Name : 'Test1'},
    //   { RequestId : '2', Name : 'Test2'},
    //   { RequestId : '3', Name : 'Test3'}
    // ],
    request: RequestInitial,
    requestId: '0'
};

// Create a reducer function with switch state for each action in action.ts
export const requestReducer = createReducer(
  requestInitialState,
  on(UpdateRequest, state => ({
      ...state,
      request : state.request,
  })),
  on(LoadAllRequests, (state , { requestCollection}) => ({
    ...state,
    requestCollection : state.requestCollection
     ]
  })),

);

request.actions.ts

import {createAction, props} from '@ngrx/store';
import { Request } from '../models/request.model';

export const UpdateRequest = createAction(
  '[Request] UpdateRequest',
  props<{request: Request}>()
);
export const LoadAllRequests = createAction(
    '[Request] LoadAllRequests',
    props<{requestCollection: Request[]}>()
);
export const DeleteRequest = createAction(
    '[Request] DeleteRequest',
    props<{requestID: Request['RequestId']}>()
);
export const loadRequestFailure = createAction(
  '[Request] ErrorRequest',
  props<{error: any}>()
);

request.component.html

<button click="LoadRequests()">Load All Requests</button>

I'm facing an issue where the payload data doesn't seem to be updating the requestCollection when executing the LoadRequests() method through the dispatch. This situation has left me puzzled as I aim to establish a seamless flow of passing data from the dispatch method to actions and eventually to the reducer for updating the store.

Answer №1

Issue detected in the request.component.html file due to incorrect binding.

<button (click)="FetchRequests()">Retrieve All Requests</button>

In addition, make sure to include payload usage within the reducer function:

on(FetchAllRequests, (state, { updatedRequestData }) => ({
    ...state,
    requestData: updatedRequestData
})),

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

My inquiry was met with silence from the Angular project

I have encountered an issue with my dockerized angular project. Upon starting my container, it appears that the 4200 port is already in use, even though the CMD command within the container does not initiate the application startup. Here is how my Docke ...

Issues arise when trying to implement Angular class and it does

I'm currently facing some challenges using classes in Angular to simplify my coding process. So far, I haven't been able to get it to work properly. Below is the code snippet I'm working with and the error message that pops up: import { Wiz ...

Error: Azure AD B2C user login redirect URI is not valid

Currently working on setting up user login with Azure AD B2C. I have successfully created an App Registration in my B2C tenant and specified http://localhost:3000 as the redirect URI. However, when implementing it in my React app using the MSAL React libra ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

Vue.js 3 with TypeScript is throwing an error: "Module 'xxxxxx' cannot be located, or its corresponding type declarations are missing."

I developed a pagination plugin using Vue JS 2, but encountered an error when trying to integrate it into a project that uses Vue 3 with TypeScript. The error message displayed is 'Cannot find module 'l-pagination' or its corresponding type ...

How to apply a single pipe to filter columns in Angular 2 with an array of values

I need to sort through an array of objects using multiple array string values. Here is an example of how my array of objects looks like: [{ "name": "FULLY MAINTAINED MARUTI SUZUKI SWIFT VDI 2008", "model": "Swift" }, { "name": "maruti suzuki ...

When null is assigned to a type in Typescript, it does not result in an error being triggered

Could someone enlighten me on why this code is not causing an error? import { Injectable } from '@angular/core'; interface Animal{ name: string; } @Injectable() export class AnimalService { lion: Animal = null; constructor() {} get(){ ...

Issue with ngmodel causing placeholder in Angular 2 md-input to not move up

While working with Angular Material to style an input field, I noticed that the placeholder does not move up when there is a value in the input. This behavior occurs only when using ngModel to bind the input. Interestingly, clicking on the input causes the ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

Guide to linking two input fields using a single datepicker

To achieve the goal of filling two input fields simultaneously, take a look at the following code snippet: <mat-form-field> <input matInput [matDatepicker]="startDate" formControlName="SaleDate" /> ...

Is it acceptable to use JavaScript files in the pages directory in NEXTJS13, or is it strongly advised to only use TypeScript files in the most recent version?

In the previous iterations of nextJS, there were JavaScript files in the app directory; however, in the most recent version, TypeScript files have taken their place. Is it still possible to begin development using JavaScript? I am working on creating an a ...

Testing a reusable component in Angular using unit testing techniques

Currently, I am creating a test for an AppleComponent which has the following type: <T,U extends BananaComponent<T>>. This component also contains BananaComponent<T>. Target Component export class AppleComponent<T,U extends BananaCom ...

The stacked bar chart in Apex is not displaying correctly on the x-axis

Currently, I am utilizing the Apex stacked bar chart within my Angular 16 project. In this scenario, there are 4 categories on the x-axis, but unfortunately, the bars are not aligning correctly with the x-axis labels. The data retrieved from my API is as ...

What is the best way to compress a file for transfer to a server using gzip?

While attempting to upload a file and send it to the server via a REST API, I am looking for a reliable method to gzip the file. Unfortunately, there is limited documentation available on this topic. Can anyone suggest the most effective approach to achiev ...

After the introduction of ReactiveFormsModule, the functionality of the Angular router has ceased

I am working on setting up a reactive form in Angular for a login page. Here is my login form: <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)"> <div class="form-group"> <label for="username">Username</label> ...

Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their ID ...

The utilization of the rest parameter in combination with generics

I encountered an issue with my iteration. The error message "Operator '+=' cannot be applied to types 'number' and 'T'" is showing up. I am puzzled as to why this is happening. let a: number = 1, b: number = 2, c: number ...

Angular 2: Embracing the Power of Hierarchical Selection

My goal is to create cascading selects where each option in a dropdown menu can lead to its own set of unique child options. This will result in a hierarchical structure of selectable items. To accomplish this, I have defined a class named fieldSelect tha ...

Error message possibly undefined when attempting to apply fill gradient to Highcharts area-spline chart

Currently working with angular 12 and utilizing highcharts. I've been attempting to fill the area spline color with a gradient, but have encountered an error in the process. Any suggestions on how to resolve this issue or what step may be causing the ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...