How can you implement a null filter in the mergeMap function below?

I created a subscription service to fetch a value, which was then used to call another API. However, the initial subscription API has now changed and the value can potentially be null. How should I handle this situation? My code is generating a compile error in oc.id as it may possibly return null.

 getE$ = createEffect(() => this.actions$.pipe(
ofType(ActionType.A),
switchMapTo(this.store.select(selectP)),
mergeMap((oc) => this.reviewService.findByR(oc.id,
  new Date(new Date()),
  new Date(new Date()), 'A')
  .pipe(
    mergeMap(d => {
      return of(LoadSuccess({ reviews: getReviews(d) }));
    }
    ),
    catchError(error => {
      return of(LoadFailure({ error: error }));
    })
  )
)));

Answer №1

In order to remove any potential null values that may be returned by the API, it is recommended to implement a call to the filter operator within our data processing pipeline, specifically between the switchMapTo and mergeMap methods.

import {filter} from 'rxjs/operators';

getE$ = createEffect(() => this.actions$.pipe(
    ofType(ActionType.A),
    switchMapTo(this.store.select(selectP)),
    // exclude `null` or `undefined` items
    filter(notNullOrUndefined)
    // securely access `oc`
    mergeMap(oc => this.reviewService.findByR(oc.id,
            new Date(new Date()),
            new Date(new Date()), 'A'
        )
        .pipe(
            mergeMap(d => of(LoadSuccess({ reviews: getReviews(d) }))),
            catchError(error => of(LoadFailure({ error: error })))
        )
    )));

The notNullOrUndefined function serves as a type guard that checks each element for validity. This approach is beneficial when dealing with arrays as well.

export function notNullOrUndefined<T>(x: T | null | undefined): x is T {
    return x !== null && x !== undefined;
}

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

Ensuring File Size and Format Compliance in Angular's HTML and TypeScript

I'm currently tackling a file upload feature on an ASP.net webpage using Angular. I have a question: How can I verify if the uploaded file is either a PDF or JPG and does not exceed 2MB in size? If these conditions are not met, I would like to displa ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

Endpoint path for reverse matching in Mongodb API

I am currently in the process of setting up a webhook system that allows users to connect to any method on my express server by specifying a method and an endpoint to listen to (for example PUT /movies/*). This setup will then send the updated movie to the ...

What is the best way to add a repository in Nest.js using dependency injection?

I am encountering an issue while working with NestJS and TypeORM. I am trying to call the get user API, but I keep receiving the following error message: TypeError: this.userRepository.findByIsMember is not a function. It seems like this error is occurring ...

The "VsTsc" operation was unable to start due to issues with its provided input parameters

Encountering the following error when building an Asp.NetCore project in Visual Studio Enterprise 2017 Version 15.6.0. The error sometimes disappears upon restarting Visual Studio, but a permanent solution has not been found. Error MSB4064: The "Compu ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

Unable to expand the dropdown button collection due to the btn-group being open

Having trouble with the .open not working in Bootstrap 4.3 after adding the btn-group class to open the dropdown... I am looking for a way to load the dropdown without using JavaScript from Bootstrap. This is the directive I am trying to use: @Host ...

Exploring the process of manually establishing a route change stream in Angular versus utilizing the features of the @angular/router module

Why would a developer choose to manually create a stream of route changes instead of utilizing Angular's ActivatedRoute as recommended in the Angular guide? export class HeroListComponent implements OnInit { heroes$: Observable<Hero[]>; pr ...

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 ...

Having trouble getting Jest to manually mock in Nestjs?

When setting up a mock service like this: // /catalogue/__mock__/catalogue.service.ts export const CatalogueService = jest.fn().mockImplementation(() => { return { filterRulesFor: jest.fn().mockImplementation((role: Roles): Rule[] => rules.filt ...

A guide to adding a delay in the RxJS retry function

I am currently implementing the retry function with a delay in my code. My expectation is that the function will be called after a 1000ms delay, but for some reason it's not happening. Can anyone help me identify the error here? When I check the conso ...

While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop. Consider this straightforward code snippet: this.filters['1','2','3'....]; for (let i = 0; i < this.filters.length; i+ ...

I am puzzled by this error in Typescript: "Why does the element have an 'any' type when the Object type lacks an index signature?"

Looking to extract an array of keys from an object with nested properties, my current code: public static getKeys(obj: Object) { let keys: string[] = []; for (let k in obj) { if (typeof obj[k] == "Object" && obj[k] !== null) { ...

How to Switch to a Different Tab in a NativeScript TabView

I'm struggling to figure out how to programmatically navigate to a different tab within a tabView from a partial View. Each tab is located in a child folder with its own html, ts, js, and css files. In this scenario, when a user clicks on an item in a ...

`The flaw in filtering logic - an analysis`

Looking to find matching records within two Lists. We have a List called allAnimals with attributes like animalId, and another List named domesticAnimals also containing animalId. The goal is to compare the two lists and create a new list where the anima ...

Is the graphql codegen accurately generating the types?

I'm in the process of developing a basic Next.js application with TypeScript by integrating Strapi as a headless CMS. The main goal is to use Strapi and GraphQL, along with TypeScript, to display content on the Next.js app. Within Strapi, there is a ...

Exploring nested contexts in react testing library with renderHook

This is a sample code snippet in TypeScript that uses React and Testing Library: import React, { FC, useEffect, useMemo, useState } from 'react'; import { renderHook, waitFor } from '@testing-library/react'; interface PropsCtx { inpu ...

Instructions on transferring information from the app.component to its child components

I am currently working with Angular 6 and I have a specific requirement. I need to send data retrieved from an external API in my app.component to other child components. Instead of repeatedly calling the common API/service in every component, I want to ma ...

Steps for utilizing Bazel to compile TypeScript

Calling all Bazel (Blaze) experts: I'm curious about the best method for integrating Bazel as a build system for cutting-edge web applications built in Typescript. Is there a preferred setup or perhaps a template that demonstrates this integration? T ...

Discovering the origins of the node.js native modules and delving into the intricacies of typed modules

I am using a Windows machine and trying to locate where node fetches the source code for native modules. On my system, I can only find the @types file which contains "Typed Only" modules. For example, the module "assert" is available in the master/lib fold ...