Strategies for Dealing with 'No Search Results' in Your Search Functionality

I am currently facing an issue with displaying "No Results Found" when a user utilizes my search feature. The current problem is that "No Results Found" appears immediately on the screen and then disappears while a search query is being processed, only to reappear if no results are found. Ideally, I would like "No Results Found" to display only after a search query has been triggered and evaluated. Is there a more effective way to achieve this rather than using a timeout method? Below is the function code I have implemented:

public get noResultsFound(): boolean
{
    if (this.query && !this._isSearching && !this.hasResults) {
        return true;
    }
}

Below is how I have structured my view code:

<div *ngIf="inputHasFocus && noResultsFound" class="no-results-found">No Results Found</div>

Answer №1

Looking for a solution? Promises might be the answer! 😄 Check out this link for more information on Promises.

Here's a simplified version of how you can use promises in your code:

search = (paramObj): Promise<SomeDataClass> => {
    // Your search logic goes here
}

requestSearch() {
    this.search(null).then((result) => {
        if (result.length === 0)
        {
            // Handle case when there are no results
        }
        else{
            // Show the results here
        }
    })
}

If you want to see a more comprehensive example, check out this snippet:

class example {
    public someBool = false;

    public search = (paramObj): Promise<Array<string>> => {
        this.someBool = !this.someBool;
        return new Promise<Array<string>>((resolver) => {
            // Simulating a time-consuming operation
            setTimeout(() => {
                if (this.someBool) {
                    resolver([]);
                } else {
                    resolver(["hi","there"]);
                }
            }, 1000)
        });
    }

    public requestSearch() {
        this.search(null).then((result) => {
            if (result.length === 0) {
                console.log("No results found")
            }
            else {
                console.log(result)
            }
        })
    }
}

Answer №2

By making a simple adjustment to the function's logic, I was able to avoid the need for a debounce timeout and prevent the premature triggering of "No Results Found". Here is the updated code snippet that resolved the issue:

public checkForNoResults(): boolean
{
    if (!Object.isNullOrUndefined(this._results) && this._results.length < 1) {
        return true;
    } 
}

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

There seems to be an issue with the functionality of Array.filter when trying to use it with arrays

I am facing an issue with filtering branchId from an Array. Here is the code snippet and steps I have taken. const [branchID,setBranchID]=React.useState([]); const tempTwo=[ { branchId: "61b25e0ae177d62ce4cb3b47", bra ...

Display the uploaded images from uploadify on the webpage

I am currently working on a PHP website that utilizes uploadify for users to upload portfolio images. While I have successfully implemented uploadify, I am now exploring the most effective way to display these uploaded images on the webpage without requir ...

Employing eval for parsing the JSON data

function ajaxFunction(){ var ajaxRequest; // The variable that enables the use of Ajax technology! try{ // Compatible with Opera 8.0+, Firefox, and Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // For Internet Explorer Browsers ...

Execute a batch file to initiate the npm start command

I'm currently working on an Angular application and I'm looking to streamline the startup process. Instead of manually running "npm start" in the console, I want to create a batch file that will automatically run "npm install" for me. Here is the ...

Stopping Form Submission with MUI TextField

I am currently creating a form using React along with MUI. I'm trying to figure out how to prevent the form from being submitted when the user hits the enter key. Usually, I would use e.preventDefault(), but for some reason it's not working in th ...

Extracting Client's True IP Address using PHP API

Utilizing the following api: I am able to retrieve country, city, and real IP address in localhost (127.0.0.1) successfully. However, when I implement this code on my website, it displays the server's address instead of the client's. How can I r ...

Monitoring User Interactions for Maintaining Session Foresight Plan utilizing RxJS

My goal is to maintain user session activity by implementing a system that locks an interactive session after 15 minutes of user inactivity (defined as no keyboard or mouse activity). The information system will automatically lock the session if there is ...

Avoiding Memory Leaks and Managing JS Heap Size While Polling Large Amounts of Data Every 5 Seconds with Vuex

I'm currently working on a Vue application that utilizes Vuex for state management. Within this application, I have several store modules set up at the root level. Periodically, every 5 seconds, I retrieve a large amount of data and update the store s ...

Ways to troubleshoot the "TypeError: Cannot read property 'value' of null" issue in a ReactJS function

I keep encountering a TypeError: Cannot read property 'value' of null for this function and I'm struggling to pinpoint the source of the issue. Can someone help me figure out how to resolve this problem? By the way, this code is written in R ...

Incorporate external JavaScript libraries not built with Angular

Our project utilizes NPM in conjunction with Browserify for managing third-party dependencies, which pairs well with AngularJS due to the CommonJS-modules. Below is a code snippet showcasing the dependency structure that integrates seamlessly with Angular ...

The onFocus event ceases to trigger once the modal popup appears

One issue that I am facing is with an onfocus event handler. Initially, everything works perfectly after the page loads. However, when I click on a link that triggers a modal popup, the onfocus event stops working. Although focus continues to work as expec ...

How to process JSON data that includes a function

I'm trying to replicate a similar diagram using dynamic input data. Here is a basic example of how I'm attempting to achieve this: <script> var myYears = ', 1991, 1992, 1993, 1994, 1995, 1998'; //auto-generated var myValues = ...

The absence of defined exports in TypeScript has presented a challenge, despite attempting various improvement methods

I've exhausted all available resources on the web regarding the TypeScript export issues, but none seem to resolve the problem. Watching a tutorial on YouTube, the presenter faced no such obstacles as I am encountering now. After updating the tsconf ...

The icons from FontAwesome in Vue do not update when computed

I am seeking a way to dynamically change the header icon based on a conversation property. <a class="navbar-item" :title="$t('header.lock')" @click="makePrivate"> <i class="fas" :class="getLockClass"></i> </a> These ...

Error: Missing semicolon at line 1005 in Vue computed function. Vetur is indicating this issue

As a beginner in vue3, I am venturing into building some side projects. However, I keep encountering an error message stating ';' expected.Vetur(1005) when attempting to utilize the computed function. Strangely enough, sometimes the same syntax w ...

What is the process for generating a new array of objects by leveraging the contents of two given arrays?

In my data collection, I have multiple objects stored in arrays like so: tableCols = [ { "id": 50883, "header": "ABC", "operator": "Sum", "order": 2 }, ...

When integrating Stripe into my Next.js application, I encounter a build error

I encountered an error when building my Next.js app with Stripe integration using "yarn build". However, when running the app locally with "yarn dev", it works perfectly without any errors. I'm struggling to figure out why this discrepancy is happeni ...

Leveraging JavaScript to determine whether a number is even or exiting by pressing the letter "q"

The main goal is to have the user input a number to check if it is even, or enter 'q' to exit the program. var readlineSync = require('readline-sync'); var i = 0; while (i <= 3) { var num = readlineSync.question ...

What is the best way to apply a consistent set of values when altering fields conditionally in dynamically generated fields within Angular?

I just finished developing a dynamic row that consists of 2 dropdowns and a text field. Users have the ability to add or remove additional rows as needed. There is a specific condition in place: if the first dropdown value is 'Date' and the seco ...

Javascript - readjust weight distribution accordingly when a weight is removed

I am in possession of a dataset that shows the proportion of each test contributing to the final grade. In cases where a student has missed one or more tests, the weight is redistributed accordingly among the tests they did take. I want to determine how ...