transmit information from the current state to a fresh task within an rxjs effect

My goal is to access state data and use it as properties for a new action. I successfully extracted the necessary data from the state after triggering the effect, but I am facing an issue when dispatching the new action with the data. It seems that I am unable to pass the arguments activeUser and activeTask to the

of(GetInstances({activeUser, activeTask}))
part in the final line of code.

@Effect()
updateInstanceLabelSuccess$ = this._actions$.pipe(
  ofType<Action>(EInstanceActions.UpdateInstanceLabelSuccess),
  concatMap(action => of(action).pipe(
    withLatestFrom(combineLatest(
      [this._userStore.pipe(select(selectActiveUser)),
        this._userStore.pipe(select(selectActiveTask))]
    ))
  )),
  tap(([action, [activeUser, activeTask]]: [Action, [User, Task]]) => {
    console.log(activeUser, activeTask);
    // activeUer and activeTask successfully loaded
    // pass activeUser + activeTask to props of Action GetInstances
  }),
  // activeUser and activeTask can´t be passed to new GetInstances Action
  switchMap(([action, [activeUser, activeTask]]: [Action, [User, Task]]) => of(GetInstances({activeUser, activeTask})))
);

Is there a way to effectively pass the parameters activeUser and activeTask to a new GetInstances Action?

EDIT:

I managed to resolve the issue with the following code snippet. Would this be considered a valid solution to the problem?

@Effect()
updateInstanceLabelSuccess$ = this._actions$.pipe(
  ofType<Action>(EInstanceActions.UpdateInstanceLabelSuccess),
  concatMap(action => of(action).pipe(
    withLatestFrom(combineLatest(
      [this._userStore.pipe(select(selectActiveUser)),
      this._userStore.pipe(select(selectActiveTask))]
    ))
  )),
  map(([action, [activeUser, activeTask]]: [Action, [User, Task]]) => GetInstances({userID: activeUser.id, taskID: activeTask.id}))
);

Answer №1

Impressive job with that code! It's a valid approach.

If I'm not mistaken, there might be room for improvement by simplifying it like so:

@Effect()
updateInstanceLabelSuccess$ = this._actions$.pipe(
    ofType<Action>(EInstanceActions.UpdateInstanceLabelSuccess),
    withLatestFrom(
        this._userStore.pipe(select(selectActiveUser)),
        this._userStore.pipe(select(selectActiveTask)),
        (action, activeUser, activeTask) => [activeUser, activeTask]
    ),
    map(([activeUser, activeTask]): [User, Task]) => GetInstances({userID: activeUser.id, taskID: activeTask.id}))
);

In this case, I'm leveraging the various options of withLatestFrom, including a final projection function that eliminates unnecessary data handling.

An alternative recommendation is creating a composite selector from those existing two. While it may seem excessive, using this method can lead to improved performance due to the caching effect of selector results.

Great work on cracking that challenge!

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

Getting started with TypeScript in combination with Node.js, Express, and MongoDB

I'm a beginner in working with TypeScript, Node.js, Express, and MongoDB. I need guidance on the end-to-end flow for these technologies. Can someone please suggest steps or provide links for a step-by-step process? What is the procedure to compile/r ...

Error: setPosition function only accepts values of type LatLng or LatLngLiteral. The property 'lat' must be a numerical value in agm-core agm-overlay

Currently, I am utilizing Angular Maps powered by Google @agm-core and agm-overlay to implement custom markers. However, when using the (boundsChange) function on the agm-map component, an error occurs with the message "invalidValueError: setPosition: not ...

Could the repeated utilization of BehaviorSubject within Angular services indicate a cause for concern?

While developing an Angular application, I've noticed a recurring pattern in my code structure: @Injectable(...) export class WidgetRegsitryService { private readonly _widgets: BehaviorSubject<Widget[]> = new BehaviorSubject([]); public get ...

Troubleshooting Missing Exports from Local Modules in React Vite (Transitioning from Create React App)

I have encountered an issue while trying to import exported members from local nodejs packages in my project. Everything was working fine with the standard CRA webpack setup, but after switching to Vite, I started getting the following error: Unca ...

Utilizing the adapter design pattern in Angular with TypeScript for enhancing a reactive form implementation

I've been struggling to understand how to implement the adapter pattern in Angular6. Despite reading numerous articles and tutorials, I still can't quite grasp the concept. Could someone provide some insights on this topic? Essentially, I have a ...

What is the process for obtaining a literal type from a class property when the class is passed as an argument, in order to use it as a computed property

Just a moment ago I posted this question on Stack Overflow, and now I have a follow-up query :) Take a look at this code snippet: import { ClassConstructor } from "class-transformer"; import { useQuery as useApolloQuery } from "@apollo/clie ...

Karma Test Requirement: make sure to incorporate either "BrowserAnimationsModule" or "NoopAnimationsModule" when using the synthetic property @transitionMessages within your application

TEST FILE import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform- browser/animations'; import { ManagePageComponent } from './manage-page.component& ...

The error message indicates a change in the binding value within the template, resulting in an

This is the structure of my component A : <nb-tab tabTitle="Photos" [badgeText]="centerPictures?.pictures?.length" badgePosition="top right" badgeStatus="info"> <app-center-pictures #centerPictures [center]="center"> ...

Is there a way to see the countdown timers in Angular 7?

Is there a way for me to view my timer's countdown as it starts? I have attempted to bind it to a variable, but all I see is [object Object]: setTime(time) { if (this.settime >= 5 ) { this.currentTime = time; this.alerttime = thi ...

When trying to use TypeScript with next.js, encountering an unexpected token `?` error is not

Having an issue with next.js, the command npm run dev keeps failing due to a syntax error related to an optional property in a tsx file: Syntax error: Unexpected token 44 | 45 | type State<T_HT> = { > 46 | ghostHighlight: ?{ | ...

Exploring TypeScript nested interfaces and types within VSCode

I often find myself hovering over functions or objects in VSCode with TypeScript to inspect their type. However, many times the types and interfaces of these objects are dependent on other interfaces and types, making it difficult to get detailed informat ...

The error message "InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' in Angular 6 and Firebase" indicates a problem with the data being passed to the AsyncPipe in

**Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'. ** I am encountering a problem with unsubscribing from the observable. My Angular-cli version is 6.0.3 This is the HTML code in home.component.html <div class ...

Exploring the depths of Typescript: Navigating through intricate mapping of keys and types in dynamic

Explaining this may be a bit tricky, but I'll start with stating my objective and then elaborate on the question as clearly as possible: Note: The version of typescript doesn't matter to me, any solution would be appreciated. interface Type {} ...

Unusual Interactions between Angular and X3D Technologies

There is an unusual behavior in the x3d element inserted into an Angular (version 4) component that I have observed. The structure of my Angular project is as follows: x3d_and_angular/ app/ home/ home.component.css hom ...

Retrieving a specific data point from the web address

What is the most efficient way to retrieve values from the window.location.href? For instance, consider this sample URL: http://localhost:3000/brand/1/brandCategory/3. The structure of the route remains consistent, with only the numbers varying based on u ...

Retrieving attributes from a reactive object in TypeScript

I have a question regarding accessing values in Typescript. Whenever I load my website, I make a call to a service that fetches user data. private currentUserSource = new ReplaySubject<IUser>(1); currentUser$ = this.currentUserSource.asObservable ...

Menu with options labeled using IDs in FluentUI/react-northstar

I'm currently working on creating a dropdown menu using the FluentUI/react-northstar Dropdown component. The issue I'm facing is that the 'items' prop for this component only accepts a 'string[]' for the names to be displayed ...

The 'import type' declaration cannot be parsed by the Babel parser

Whenever I attempt to utilize parser.parse("import type {Element} from 'react-devtools-shared/src/frontend/types';", {sourceType: "unambiguous"}); for parsing the statement, I come across an error stating Unexpected token, exp ...

Initialization of an empty array in Typescript

My promises array is structured as follows: export type PromisesArray = [ Promise<IApplicant> | null, Promise<ICampaign | ICampaignLight> | null, Promise<IApplication[]> | null, Promise<IComment[]> | null, Promise<{ st ...

What is the syntax for implementing this function in TypeScript?

When developing applications in react and typescript, I find myself frequently creating helper functions. However, there are two key points that always give me pause. One of my functions is provided below, showcasing the common dilemmas I face. What shoul ...