简体   繁体   中英

Trying to debounce search function calls results in no event passed to a function

I am working with a library named lodash using its debounce() function to sort of limit api calls for search suggestions ie instead of calling api every time user changes a field I debounce it and wait 300ms from when they finish typing:

it looks like this in my component:

class myComponent extends Component {

  //Handle listing search
  searchListing(event) {
    console.log(event.target.value);
  }

  //Render
  render() {
    const listingSearch = _.debounce( () => { this.searchListing() }, 300  );

    return (
        <TextInput onChange={listingSearch}/>

    );
  }
}

it works and calls the function however I get an error saying: Uncaught TypeError: Cannot read property 'target' of undefined

So I tried passing an event like so:

const listingSearch = _.debounce( (event) => { this.searchListing(event) }, 300  );

Now error says: Uncaught TypeError: Cannot read property 'value' of null after inspecting this event I'm passing, I can see that it has empty target, so is not working correctly.

Solution to my problem was to include event.persist(); inside my onChange handler function.

So:

  searchListing(event) {
    event.persist();
    console.log(event.target.value);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM