-2

Using npm debounce I get an error with the following code in ReactJS. The error

Javascript - Uncaught TypeError: Object(...) is not a function

happens when the function is passed into debounce()

import React, { Component } from 'react';
import { debounce } from 'debounce';

class test extends Component {
     constructor(props) {
         super(props);
         this.state = {
             yolo: {}
         };
     }

     foobar(param) {
         debounce(() => {
             this.setState({yolo: param});
         }, 99);
     }

     render () {
         return (
             ...
             <SomeComponent action={this.foobar.bind(this)} />
             ...
         );
     }
}

I have tried some of the solutions mentioned in Perform debounce in React.js but none seem to work.

Ulsting
  • 491
  • 2
  • 6
  • 17

1 Answers1

1
import React, { Component } from 'react';
import debounce from 'debounce';

class test extends Component {
     constructor(props) {
         super(props);
         this.state = {
             yolo: {}
         };
         this.foobar.bind(this);
     }

     foobar(param) {
         debounce(() => {
             this.setState({yolo: param});
         }, 99);
     }

     render () {
         return (
             ...
             <SomeComponent action={this.foobar.bind(this)} />
             ...
         );
     }
}

The top set of code should work. Ok, so the reason why your call to foobar was not working before was because you were missing this line: this.foobar.bind(this);. Your previous syntax worked just fine and is actually preferable to the this.foobar =. Reason being because one is ES6 syntax and the other is ES5. What that bind function does when you call it is attach a particular this context for when the function is called. Here is a reference to an article that explains that: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Now the second part of this was the import. when you use the object bracket syntax, thats actually called object destructuring. So what that does is whatever that object exports it tries to access a debounce property and make that accessible in the current file. Problem is I suspect that that npm package is already export a function as its default so you don't need to access something on it. Make sense?

Hope this all helps! Best of luck (thumbsup)

miguelsolano
  • 519
  • 3
  • 11