The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached.

Do you have any insights into why this.props.onCriteriaChange is not being executed?

import * as React from 'react';
import { debounce } from 'lodash';

interface CustomerSearchCriteriaProps {
  onCriteriaChange: (criteria: string) => void;
}
interface CustomerSearchCriteriaState {
  criteria: string;
}

class CustomerSearchCriteria extends React.Component<CustomerSearchCriteriaProps, CustomerSearchCriteriaState> {

  constructor() {
    super();

    this.state = {
      criteria: ''
    };
  }

  // problematic method:
  raiseCriteriaChange = () => {
    // The call reaches here without any issues ...
    debounce(
    () => {
       // ... but for some reason, it never reaches this point ... Any ideas why?
       this.props.onCriteriaChange(this.state.criteria);
    },  
    300);
  }

  handleCriteriaChange = (e: React.FormEvent<HTMLInputElement>) => {
    this.setState({ criteria: e.currentTarget.value }, () => {
      this.raiseCriteriaChange();
    });
  }

  render() {

    return (
      <div className="input-group">
        <input
          type="text" 
          value={this.state.criteria} 
          onChange={this.handleCriteriaChange} 
          className="form-control"
        />
      </div>
    );
  }
}

export default CustomerSearchCriteria;

Answer №1

_.debounce is a useful function that generates another function which needs to be invoked. Consider updating your script as follows:

handleSearchInput = debounce(() => {
    this.props.onSearchChange(this.state.searchQuery);
}, 250);

Answer №2

Check out _.debounce, it explains how it works

(Function): Produces a new debounced function.

To use it properly, you'll need to execute it as shown below:

var debounced = debounce(
    () => {
       // ... but the call never reaches here ... why does this happen?
       this.props.onCriteriaChange(this.state.criteria);
    },  
    300
);

debounced();

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

Executing an asynchronous action without linking promises to subsequent actions

Encountered a challenge while using componentWillReceiveProps with redux async action. Below is the code snippet along with an explanation: componentWillReceiveProps(nextProps) { if(nextProps.job.status === 'applied'){ this.showAppliedDial ...

Best practices for referencing attributes created with the data method in a Vue component

In my application, there is a section that displays a list of users along with a search box to filter names. The user information is fetched from a database and stored in app.users. I have created a component named 'user' to show the details of e ...

After an error occurs, the Node.js Restify code will be executed

Within a Restify route, I have set up a router handler that calls a custom module for error checking. If the code encounters an error condition, it returns next(err) and displays the error message in the browser. However, the code does not stop executing a ...

Can the Rxjs library's Observables of() function be used to output multiple values?

I am inquiring about this because I came across in the Angular documentation that of(HEROES) returns an Observable which emits a single value - an array of mock heroes. If I cannot use of(), do you have any alternative suggestions for me? I am cur ...

Is there a way to create animated CSS box-shadow depth using jQuery or CSS3 transitions?

This code snippet applies delays but doesn't seem to update the style changes until the loop completes: for (i=20;i>=0;i--) { var boxShadow = i+"px "+i+"px "+i+"px #888"; $('article').css("box-shadow", boxShadow); ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

What is the reasoning behind deploying both the source code and node_modules?

My framework of choice is CRA ([email protected]). When I serve my app locally using webpack devserver, I can see all the expected files deployed including bundle and chunks. However, when I serve my build folder after running npm run build followed ...

What is the best way to properly format letters with accents (such as French letters)?

I have encountered a challenge where I created a PHP file to display French text and then utilized this text in an AJAX file (specifically the responseText). The issue arises when trying to show the French responseText in an alert using JavaScript, as ac ...

Unable to close Bootstrap modal upon clicking "x" or "close" buttons

Hey everyone, I'm having a bit of trouble with my modal. It appears correctly when clicked to open, and the close buttons seem to detect that my mouse is hovering over them. However, when I click on the buttons, nothing happens and the modal remains o ...

How can I change an element using jQuery's getElementById method?

My current setup involves using a web page as a server and an Arduino as a client. Whenever a specific mode is active, the Arduino sends the following code: <LED>on</LED> The server then adjusts its status accordingly based on this input. I ...

jQuery conceal input field after it has been displayed

I've created an HTML form with two different sections for search purposes. The first section displays basic fields, and by clicking on "Advanced Search" (in my case, "Расширенный поиск"), additional fields are revealed. Everything work ...

Is there a way to use jQuery to eliminate divs that contain multiple identical data values?

Is there a way to accomplish this? <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="08-March-2016"></div> <div class="chat_timestamp_group" data-date="14-March-2016" ...

Limiting the use of TypeScript ambient declarations to designated files such as those with the extension *.spec.ts

In my Jest setupTests file, I define several global identifiers such as "global.sinon = sinon". However, when typing these in ambient declarations, they apply to all files, not just the *.spec.ts files where the setupTests file is included. In the past, ...

Using React to incorporate the necessary jquery for a separate library

I am looking to incorporate Trumbowyg library into my React project, however, I have encountered an error stating that jQuery is not defined. I found information suggesting that jQuery needs to be made available as a global variable in the window object. ...

Error retrieving access token in Microsoft PowerBI due to missing 'Access-Control-Allow-Origin' header in React

I've been working on integrating Microsoft PowerBI access token into my React app, but I keep encountering an error stating 'No 'Access-Control-Allow-Origin' header is present on the requested resource' when trying to fetch the tok ...

Refresh React Native maps

I am using a progress bar (react-native-elements) that is animated with useEffect(). The issue is that this component contains a MapView(react-native-maps) which re-renders on every tick, making it impossible to interact with the map. Is there a way to ke ...

Leveraging the Firebase email trigger extension with JavaScript

Recently, I integrated the email trigger extension for Firebase. Below is the function I am using: firestore .collection("profiledata") .doc(user.uid) .update({ accountStatus: "active", }) .then(() => { // At this p ...

I'm facing difficulty in assigning props because of the specific nature of generics in Typescript

My goal is to create a Higher Order Component (HOC) that can control a component which relies on certain props to function properly. To elaborate: I want to build a HOC that takes a component expecting props value and onChange, and modifies it so that the ...

Unexpected token in catch clause in React Native TypeScript

Despite having a fully configured React Native Typescript project that is functioning as expected, I have encountered a peculiar issue: Within all of my catch blocks, due to the strict mode being enabled, typescript errors are appearing like this one: My ...

The filtering feature in the Row Group table of PrimeNG controls is malfunctioning and causing issues with the Dropdown

Within my Angular project, I have integrated PrimeNG controls version 11.4.4. Utilizing the Table control, I've structured tabular data to display rows in a grouped fashion with collapsible functionality. I've recently introduced a textbox and d ...