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

Encountering a 403 error while trying to deploy a Node.js application on Heroku

Yesterday, I encountered an issue while trying to access a Node.js application on Heroku. The error message from the Chrome console was: Refused to load the image 'https://browser-rpg-app.herokuapp.com/favicon.ico' due to Content Security Policy ...

Subscribing to valueChanges in reactive forms to dynamically update checkbox options

My goal is to create a select dropdown with options for bmw, audi, and opel. The user can only select one option from the dropdown, but they should also have the ability to select the options that were not chosen using checkboxes. cars = [ { id: 1, na ...

When utilizing makeStyles in @mui, an error may occur stating that property '' does not exist on type 'string'

I am stuck with the code below: const useStyles = makeStyles(() => ({ dialog: { root: { position: 'absolute' }, backdrop: { position: 'absolute' }, paperScrollPaper: { overflow: 'visib ...

React: Avoid unnecessary re-rendering of child components caused by a bloated tree structure

I am dealing with a tree/directory structured data containing approximately 14k nodes. The issue I am facing is that every time a node is expanded or minimized by clicking a button, causing it to be added to an 'expanded' Set in the Redux state, ...

Working with JSON data in Angular 2 constructor

When sending a JSON response from the server, it is in the format shown below: {id: Int, name: String, childJSON: String} I want to map this data to the following TypeScript classes: export class Student{ constructor(public id: string, ...

Troubles arise when compiling TypeScript to JavaScript

I have been experimenting with TypeScript, specifically for working with classes. However, I am facing an issue after compiling my TS file into JS. Below is the TypeScript code for my class (PartenaireTSModel.ts): export namespace Partenaires { export ...

Angular compilation alerted about a missing export: "ɵɵdefineInjectable was not located within '@angular/core'

I'm having an issue while trying to run my Angular application. The error message related to the "ngx-mqtt": "^6.6.0" dependency keeps popping up even though I have tried changing the versions multiple times. I am using CLI 6.2.9 and cannot seem to re ...

Modify data in a table using Dialog Component in Angular Material

I need to implement a Material Dialog feature that allows users to update entries in a table by clicking on the "Change Status" button. Check out this functional snippet: https://stackblitz.com/edit/angular-alu8pa I have successfully retrieved data fr ...

Is it feasible to alter the file name while utilizing express-fileUpload library?

Is there a way to modify the file name of an uploaded file on the server side? app.post(URL, (req, res) => { let fileName = req.files.file.name; req.fileUpload; res.statusCode = HTTP_OK; res.send("Good Job") }) The settings I have in uploadF ...

Creating one-to-one relationships in sequelize-typescript can be achieved by setting up multiple foreign keys

I have a question about adding multiple foreign keys to an object. Specifically, I have a scenario with Complaints that involve 2 Transports. One is used to track goods being sent back, and the other is used for goods being resent to the customer. @Table({ ...

TS - The 'new' keyword can only be used with a void function

I'm encountering a strange TypeScript error: "Only a void function can be called with the 'new' keyword." What in the world? https://i.sstatic.net/bKAUT.png The constructor function looks like this: function Suman(obj: ISumanInputs): ...

Issue with bootstrap modal new line character not functioning properly

Is there a correct way to insert a new line for content in a modal? I have this simple string: 'Please check the Apple and/or \nOrange Folder checkbox to start program.' I placed the '\n' newline character before "Orange," e ...

NextAuth is failing to create a session token for the Credential provider

Currently, I am in the process of developing an application using the t3 stack and am facing a challenge with implementing the credential provider from nextauth. Whenever I attempt to log a user in, I encounter an error in the console displaying the messag ...

Utilize React to transform PDF files into PNG images and seamlessly upload them to Cloudinary

Currently, I am utilizing react typescript and looking to select a PDF file, transform the PDF into an image, and then upload the final image onto Cloudinary. Although I have a service set up for uploading images in my Cloudinary media library, I am unsu ...

Call a function within a stateless component in a React application

I have a question regarding my React component. I am attempting to call the function ButtonAppBar within my stateless component, but the TypeScript compiler is throwing an error stating '{' expected. I'm unsure whether I need to pass it to m ...

What causes an array to accumulate duplicate objects when they are added in a loop?

I am currently developing a calendar application using ExpressJS and TypeScript. Within this project, I have implemented a function that manages recurring events and returns an array of events for a specific month upon request. let response: TEventResponse ...

Extracting data from HTML elements using ngModel within Typescript

I have an issue with a possible duplicate question. I currently have an input box where the value is being set using ngModel. Now I need to fetch that value and store it in typescript. Can anyone assist me on how to achieve this? Below is the HTML code: ...

Looking for a TypeScript annotation that allows accessing an object property using a variable

When working with plain JavaScript, we have the ability to access an object's property value using a variable. For example, this is permitted: let obj = { a: 100, b: 'Need help with TypeScript', c: new Date() }; let prop = 'b'; c ...

Warning from Cytoscape.js: "The use of `label` for setting the width of a node is no longer supported. Please update your style settings for the node width." This message appears when attempting to create

I'm currently utilizing Cytoscape.js for rendering a dagre layout graph. When it comes to styling the node, I am using the property width: label in the code snippet below: const cy = cytoscape({ container: document.getElementById('cyGraph&apo ...

Angular version 5 and above introduces a new feature called "openFromComponent" within the Snackbar component, facilitating seamless communication

Angular (v5.2.10) Snackbar --| Introduction |-- I am facing a scenario where an Angular component named "Parent" is initializing an Angular Material Snackbar known as snackBar. The snackbar is being passed in the component called SnackbarMessage, which ...