The takeUntil function will cancel an effect request if a relevant action has been dispatched before

When a user chooses an order in my scenario:

selectOrder(orderId): void {
  this.store$.dispatch(
    selectOrder({orderId})
  );
}

The order UI component triggers an action to load all associated data:

private fetchOrderOnSelectOrder(): void {
  this.store$.select(selectSelectedOrder).pipe(filter((selectedOrder: Order | null): selectedOrder is Order => Boolean(selectedOrder)))
    .subscribe((selectedOrder: Order) => {
      this.store$.dispatch(getOrder({
        orderId: selectedOrder.id
      }))
    }
  );
}

An effect waits for this action to send a request to the server:

public getOrder$ = createEffect(() =>
        this.actions$.pipe(
            ofType(getOrder),
            switchMap((props: GetOrderProps) =>
                this.orderService.getOrder(props.orderId).pipe(
                    map((order: Order) =>
                        /* Logic for successfully received order */
                    ),
                    catchError((error: HttpErrorResponse) =>
                        /* Logic for failure */
                    ),
                    takeUntil(this.actions$.pipe(ofType(selectOrder))),
                ),
            ),
        ),
    );

Take notice of the takeUntil line, as it seems to be causing an issue. I included it to cancel any ongoing request when selecting a new order, assuming we don't need the previous result anymore. However, this seems to immediately cancel all requests, preventing me from retrieving any orders at all.

Why does this unexpected behavior occur? As far as I can tell, the request should happen after the select order action, so why is its corresponding observable being affected by it?

Answer №1

What is the purpose of using the takeUntil operator?

It helps in cancelling a pending request once a new order is selected, as switchMap handles fetching orders for the newly selected order.

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

What is the process for creating static pages that can access local data within a NextJS 13 application?

I recently completed a blog tutorial and I must say, it works like a charm. It's able to generate dynamic pages from .md blog posts stored locally, creating a beautiful output. However, I've hit a roadblock while attempting what seems like a sim ...

The declaration file for the module 'vue-html-to-paper' was not located

Struggling to make a sample project work with HTML to PDF, but encountering an error message stating: Could not find a declaration file for module 'vue-html-to-paper' Even though it resides in my node_modules index.js import Vue from 'vue& ...

Export interface for material-ui wrapper to cast any type in TypeScript (React)

I work with React using TypeScript. Recently, I encountered an issue with exporting. I'm creating an interface that encapsulates components from Material-ui. Here is a simplified example: Wrapping.tsx import { default as Component, ComponentProps ...

Intercepting Nested Requests in a Nest.js Application

Can you explain how to incorporate a nested interceptor in Nest.js? I currently have two interceptors: UsersInterceptor and PostsInterceptor UsersInterceptor: @Injectable() export class UsersInterceptor<T> implements NestInterceptor<T, Response& ...

Can you explain the contrast between Angular 2 components and directives?

I have been having difficulty grasping the distinction between these two ideas within the framework. I am quite experienced with directives in AngularJS 1.x, and both components and directives in Angular 2 appear to be closely related to this concept... ...

Is the state variable not being properly set by using React's setState within the useCallback() hook?

Within a React FunctionComponent, I have code that follows this pattern: const MyComponent: React.FunctionComponent<ISomeInterface> = ({ someArray, someFunction }) => { const [someStateObjVar, setSomeStateObjVar] = React.useState({}); const [ ...

Leveraging Shared and CoreModule in Ionic

In the recommended styleguide found at https://angular.io/guide/styleguide#core-feature-module, it is suggested to implement a SharedModule and CoreModule in an Angular application. I am curious if utilizing these modules would also be beneficial in an Io ...

Leveraging the Nest JS Validation Pipe in combination with the class-transformer to retrieve kebab-case query parameters

Can someone help me with using the Nest JS Validation Pipe to automatically transform and validate my GET Request Query Params? For example: {{url}}/path?param-one=value&param-two=value In my app.module.ts, I have included the following code to impl ...

Changing the base URL in an Angular HTTPclient GET request for custom endpoint

When attempting to send a GET request to a specific URL, I'm encountering an issue where the original URL is being replaced by a different one, leading to a request being made to a non-existent URL. Below is the code snippet: import { HttpClient } f ...

The Angular mat-paginator is malfunctioning and not displaying the correct page sizes

I am facing an issue with the pagination display in my mat-table. Despite setting the page size to 5, all the results are being displayed on a single page. I fetch a list of transactions from an API and populate them in the table. I have tried various solu ...

Sort by label using the pipe operator in RxJS with Angular

I have a situation where I am using an observable in my HTML code with the async pipe. I want to sort the observable by the 'label' property, but I'm not sure how to correctly implement this sorting logic within the pipe. The labels can be e ...

Obtaining a Slick Component Instance with the help of View Child

I am a beginner in angular and I am currently working on implementing a paginated carousel using the ngx-slick plugin. However, I am facing an issue where I need the carousel to start from index 1 instead of 0 when it loads in the template. The ngx-slick p ...

Error message in Typescript with React: "The type 'ComponentClass<StyledComponentProps<{}>>' cannot be assigned to type 'typeof MyComponent'"

Currently experimenting with integrating the Material UI 1.0 (beta) @withStyles annotation into a React component. The documentation provides a JavaScript example (), however, it results in a compilation error when using Typescript. Despite the error, the ...

Find all Mondays occurring within a specified date range using Moment.js

I need to extract all Mondays within a specific date range. let start = moment(this.absence.FromDate); let end = moment(this.absence.ToDate); The user has the option to deactivate certain weekdays during this period by setting booleans. monday = true; t ...

Trigger refetchQueries post-execution of a mutation operation

In the past, I executed a mutation in a similar manner as shown below: export const useEditLocationName = () => { const [editFavoriteLocationName] = useEditFavoriteLocationNameMutation({ refetchQueries: [{ query: GetMyFavouritePlacesDocument}], ...

A versatile generic type infused with dynamic typing and optional parameter flexibility

Looking to develop a function that can accept an optional errorCallback parameter. In cases where the consumer of this function does not provide a callback, I aim to default to a preset handler. The key criteria here are strong typing and utilizing the ret ...

Is there a way to deactivate multiple time periods in the MUI Time Picker?

Recently, I have been working on implementing a Time Picker feature with two boxes: [startTime] and [endTime]. The objective is to allow the time picker to select only available times based on predefined data: let times = [ { startTime: "01:00", en ...

How to efficiently retrieve parent content from a child component

parent.html <ion-content class="project"> <ion-grid> <ion-row class="details"> <project [data]="data"></project>// this child component </ion-row> </ion-grid> </ion-content> project.ht ...

Finding the appropriate method to access a template variable reference in a designated row of an Angular Material table (Angular 7)

Currently, I am working on implementing a more intricate version of a behavior inspired by Angular Material's tutorials. In my simplified example, an Angular Material table is populated with data from a string array. The first column contains input fi ...

Verify that the lower limit is not higher than the upper limit set in an Angular application

In my Angular application, I have two input fields for minimum and maximum values. I want to display an error message if the user enters a minimum value greater than the maximum value provided, or the default maximum value if none is provided. The form is ...