What types should be used when passing a NgRx Action as a parameter to a function?

Within my Effects function, I have implemented the following code structure.

I have included a few lines of code for the catchError block to ensure that:

  1. Any errors are handled by the state/store
  2. The errors are forwarded to the global error handler / Interceptors
getItems$ = createEffect((): Observable<Action> => {
  return this.action$.pipe(
    ofType(ItemActions.getItem),
    exhaustMap(() => {
      return this.apiClient.getItems().pipe(
        map((response) => ItemActions.getItemsSuccess({ response })),

        catchError((exception: HttpErrorResponse) =>
          of(EMPTY).pipe(
            tap(() => this.store.dispatch(ItemActions.getItemsFailure({ exception }))),
            switchMap(() => throwError(() => exception)),
          ),
        ),

      );
    }),
  );
});

Since implementing this approach involves repeating 5 similar lines of code each time error handling is required, I decided to consolidate it into a separate method:

handle(action: Function, error: HttpErrorResponse, props?: object): Observable<never> {
  return of(EMPTY).pipe(
    tap(() => this.store.dispatch(action({ exception: error, ...(props && { ...props }) }))),
    switchMap(() => throwError(() => error)),
  );
}

Therefore, the catchError section now appears as follows:

catchError((error: HttpErrorResponse) => this.errors.handle(ItemActions.getItemsFailure, error)),

While this method is functional, some questions arise:

  1. What should be the appropriate type for action (Function currently works but may not be ideal)?
  2. What should be the proper type for props (object is currently used, but ideally should only allow properties specific to the associated action)?

Answer №1

  1. To achieve this, you have the option to utilize either Action or ActionCreator
  2. If you find this challenging, consider creating the action within the effect and passing its instance to handle like so:
    catchError((error: HttpErrorResponse) => this.errors.handle(ItemActions.getItemsFailure(error))), 

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

Why is the mat-toolbar and mat-toolbar-row in the footer (shared) component of Angular 6 not showing up correctly, despite no error being reported?

Despite reviewing similar questions, I have not been able to find a solution for my specific issue. I have searched through the following links but failed to find a solution: Angular Material v6 Mat-Footer - "Cannot read property 'template' of ...

Reusing methods in Javascript to create child instances without causing circular dependencies

abstract class Fruit { private children: Fruit[] = []; addChild(child: Fruit) { this.children.push(child); } } // Separate files for each subclass // apple.ts class Apple extends Fruit { } // banana.ts class Banana extends Fruit { } ...

Oops! It seems like there was an issue with trying to access a property that doesn't exist

Whenever I try to insert a new line into my table, I encounter the following error message: ERROR TypeError: Cannot read property 'Nom' of undefined at Object.eval [as updateDirectives] (MedecinsComponent.html:43) at Object.debugUpdateDirect ...

Accessing the constants and state of child components within a parent component in React

I've created a MUI TAB component that looks like this <Box sx={{ width: "100%" }}> <Box sx={{ borderBottom: 1, borderColor: "divider" }}> <Tabs value={value} onChange={handleChange} aria-label ...

Is there a way to verify the availability of an authenticated resource without triggering a pop-up for credentials in the browser?

I am facing the challenge of fetching data from a web service located on a different server without knowing if the user has an active session on that server. If the user does have a session, I want to retrieve the data automatically. However, if they do no ...

I am trying to replace the buttons with a dropdown menu for changing graphs, but unfortunately my function does not seem to work with the <select> element. It works perfectly fine with buttons though

I am currently working on my html and ts code, aiming to implement a dropdown feature for switching between different graphs via the chartType function. The issue I am facing is that an error keeps popping up stating that chartType is not recognized as a ...

Issue: Failed to Render: Error encountered during parsing of template: Element 'mat-checkbox' is not recognized as a valid element

For the purpose of testing my component, I wrote the following code snippet: describe('Component: TestComponent', () => { let component: TestComponent; let fixture: ComponentFixture<TestComponent>; beforeEac ...

Angular Error: Argument must be included in the dependency array

While making changes to a dialog form, I encountered an error. Instead of using a dialog form, I want to switch to a regular form. However, when I remove @Inject(MAT_DIALOG_DATA) from the constructor, I get an error. Any suggestions on how to resolve thi ...

Unraveling the mysteries of an undefined entity

When the variable response is undefined, attempting to retrieve its property status will result in an error: Error: Unable to access property 'status' of undefined const { response, response: { status }, request, config, } = error as A ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

Changing dot notation to bracket notation in Angular

Having trouble using dynamic columns in a Primeng table? The column fields need to be in bracket notation for this setup. What if you have a column with nested JSON structure and you're not sure how to write that in bracket notation? Don't worry, ...

"Strategically Leveraging Nested Subscriptions in Conditional Logic

In my CRUD angular 5.5 component, I utilize routing parameters to set up its different modes (new, edit, view). I am looking for a way to avoid nested subscriptions but struggle with implementing basic conditional logic. this.route.params.subscribe((p ...

Getting the mssql output in Protractor using VSCode

I recently tried running the code below and it seems like the connection is established successfully. However, I'm unable to see any output. Is there a way to view the query result? I am still learning about Protractor, NodeJS, and MSSQL connections. ...

Preventing special characters in an input field using Angular

I am trying to ensure that an input field is not left blank and does not include any special characters. My current validation method looks like this: if (value === '' || !value.trim()) { this.invalidNameFeedback = 'This field cannot ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

In React-Redux, attempting to assign a value to an empty string is not permitted

When using the useDispatch hook, I am facing an issue where I cannot set the string to an empty value. Instead, it always sets the value to the last character in the string. App.tsx const dispatch = useDispatch(); dispatch(updateLocation('')); ...

List out all the classes that implement an interface in Typescript

Greetings to all TypeScript enthusiasts! Here's a challenge I want to tackle: I aim to establish an interface -- let's name it IShape -- and define several classes (Rectangle, Circle, Triangle) that adhere to the IShape interface. Let's sa ...

"What is the best way to apply multiple filters to an array in a React

Is there a way to incorporate dropdown menus along with search text input for filtering an array in React? I would like to give users the option to select a location and then search for specific results within that location. Any suggestions on how to ach ...

Following a successful compilation, the Angular application displays an empty page

Alert: Uncaught TypeError: Cannot read property 'length' of undefined at Object./src/components/Carousel.vue (Carousel.vue:123) at __webpack_require__ (bootstrap:1024) at Module../src/main.js (main.js:1) at __webpack_require__ (b ...

What is the process for obtaining an AccessToken from LinkedIn's API for Access Token retrieval?

We have successfully implemented the LinkedIn login API to generate authorization code and obtain access tokens through the browser. Click here for image description However, we are looking to transition this functionality to an ajax or HTTP call. While w ...