When the input is null, the ngbtypeahead function throws a TypeError

I've incorporated the typeahead feature from ng-bootstrap into my Angular 8 project, using this link as a reference: https://ng-bootstrap.github.io/#/components/typeahead/examples. While implementing a function provided in the library's examples, I encountered an error when one of the inputs turned out to be null.

Within my component class, there is a variable created through a function:

searchAutofill = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(200),
      distinctUntilChanged(),
      map(term => term.length < 1 ? []
        : this.option.filter(v => v && v.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 15))
    )

The 'option' variable is an array of strings, like so:

[
    "tom",
    "bob",
    "foo",
    "emma",
    null,
    "john",
    "hello",
    "example"
]

Upon encountering the null value, the function throws an error: ERROR TypeError: "v is null". How can I modify the code to handle or ignore null values?

Answer №1

Definitely, the reason is because you are attempting to use the String method on a 'null' value.

Therefore, when executing v.toLowerCase(), you end up with null.toLowerCase().

It is crucial to always verify that the object you are accessing properties or methods from is the expected object. Establishing some validation rules for this purpose is highly recommended,

In your situation, it appears that you aim to ascertain whether the string v contains a specific substring stored in the term variable.

Based on my interpretation, it seems you intend to return false if v happens to be null:

filter(v => v && v.toLowerCase().indexOf(term.toLowerCase()) > -1)

Just a side note, in the provided code snippet I only confirmed that v is not falsy. It might be advisable to include additional checks to confirm if it is indeed a string. For example:

typeof v === 'string'

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 proper method for triggering an animation using an IF statement with A-Frame animation mixer?

I am currently exploring the capabilities of the animation mixer in A-Frame and trying to trigger a specific action when a particular animation is playing (like Animation 'B' out of A, B, C). Although I'm not well-versed in Javascript, I ha ...

Utilize JavaScript to target the specific CSS class

Hello, I am currently using inline JS in my Wordpress navigation menu, redirecting users to a login page when clicked. However, I have been advised to use a regular menu item with a specific class and then target that class with JS instead. Despite searchi ...

Having trouble associating an object with a template using ngModel?

It seems like such a simple thing to do, but for some reason I can't seem to get it right. Here is what I have in my class: interface Message { type: string; email: string; } export class MyClass { public message: Message; public email: st ...

How can one effectively transform a value into a boolean in Typescript?

Exploring the most common methods for obtaining truthy/falsy values in typescript I have come across these options: !!value Boolean(value) Specifically for strings: value !== null && value !== undefined && value !== '' And for n ...

The Custom Layout Component in Form.io

I am currently working with Form.io v3.27.1 and I'm in the process of developing a custom layout component, specifically an accordion. I have been referring to the concepts outlined in the CheckMatrix component example as my guide. Successfully, I ha ...

Integrating Javascript and JQuery in Reactjs: A Comprehensive Guide

Currently, I am working with ReactJS and utilizing the Next.js framework. My goal is to implement the provided code snippet in index.js to display data (day, month, etc.). How should I go about achieving this? Here is the code snippet: <script> fun ...

Bringing in SCSS using Typescript, React, and Webpack

I am trying to utilize .scss classes by importing them and applying them to the className property of a React component. Here is the structure of my project : root/ ... config/ ... webpack.config.js src/ ... global.d.ts app/ ...

gathering identical objects in the collection

I need to calculate the total time of the specified objects and display it in a single list. Here is the object data: var list = [ { 'user': 'Tom', time: 270547 }, { 'user': 'Alex', time: 82081 }, { 'user&apo ...

Stop the Enter key from functioning as a mouse click

Whenever an element is focused on and a mouse click action can be triggered, I've observed that the Enter key functions as if you're clicking the mouse left button. This behavior is causing conflicts in other parts of my code, so I need to find a ...

Tips for determining the return type when a function yields various promise types

A scenario in which a function returns a Promise with two different potential types based on the parameters passed to it: async function myFunction(buf: boolean): Promise<Buffer | string> { const bytes = "00"; if (buf) { ret ...

Guide to implementing the Office 365 Javascript API in your application

Looking to integrate an Office 365 Excel sheet with the necessary toolbars into my web-based application, similar to this setup (including the Excel Online toolbar above). Link Here Unsure of the process - is there a way to implement tables and toolbars ...

Looking for a way to use regular expressions (in Javascript) to split a string containing spaces and parentheses?

I'm new to regular expressions and am seeking guidance on how to split a string like the one shown below using JavaScript. The text I need to work with should be divided by a space character, but sometimes there are spaces within the text snippet as s ...

Accessing my data on my personal server through firestore entails an extra step in the request process

If I were to set up Cloud Firestore on my personal server, wouldn't that create a "two-way trip" for accessing my data? What I find concerning is the fact that the client-side has to send a request to my server first, and then my server must reach ou ...

React to the animated scaling

I'm attempting to animate the scale of my react component. Although it seems straightforward, I've run into some issues while following a similar example from the React-Motion demos: var customComponent = () => { let newStyle = { scale: sprin ...

Using Angular with CSS Grid: Avoid distributing grid items evenly in terms of width

I am working on an app that utilizes a grid with rows and columns. One of the features allows me to dynamically remove rows, causing the remaining items to evenly distribute themselves across the width of the grid. However, I now require a layout similar ...

Troubleshooting: Unable to mutate a state variable in Vuex

I am working on updating my contact list whenever a different brand is selected. The goal is to clear the array of contacts associated with the current brand and then refill it with the new brand's contacts. However, I'm facing an issue in my Vu ...

Changing field visibility in Angular Reactive form (form validation) by toggling based on a checkbox in another component

I'm facing a challenge with a complex form where the fields depend on toggling checkboxes in a separate component (parent). My goal is to dynamically validate the form, with some fields being enabled and others disabled based on the toggling of the ch ...

The modal functionality in AngularJS doesn't seem to be functioning properly

I am currently working on an Angular application where I want to implement a button that, when clicked, will open a pop-up window displaying a chart. Below is the button code: <div style="padding-top:50px;padding-left:10px;"> <button type="butto ...

How can I make the footer on my webpage have a white background?

My goal is to create a white div that spans from point (A) to point (B) on the page, just like in the image. I aim for it to stretch all the way down to cover the entire browser without showing any gray background underneath, even when the page is scrolled ...

Validation Express; the error variable is not defined in the EJS

Struggling with a perplexing issue that has been eluding me for quite some time now, I am hopeful that someone out there might be able to provide me with some guidance. The variable (error) that I am passing in the res.render{} object seems to be unattain ...