0

I am trying to import the debounce function in my VueJs project.

I ran: npm i --save lodash.debounce

Then I imported it in my project with: import { debounce } from 'lodash/debounce'

And tried using it with:

debounce(() => {
    console.log('I only get fired once every two seconds, max!')
}, 2000)

I also tried importing it as import debounce from 'lodash/debounce', but whatever I do I cannot get it to work.

I read this stack post but that also doesn't seem to work: How to Import a Single Lodash Function?

Anyone knows how to do this?

Thanks.

Reinier68
  • 2,450
  • 1
  • 23
  • 47
  • 1
    `import debounce from 'lodash.debounce`' – Shaya Ulman Nov 06 '20 at 11:05
  • Tried that aswell @ShayaUlman. But how do I actually use it in my code? Because the code example that I gave does not run or gives me errors... – Reinier68 Nov 06 '20 at 11:06
  • What are the errors? are you sure it eas correctly installed? – Shaya Ulman Nov 06 '20 at 11:07
  • If I use `this.debounce()` the error is: `this.debounce is not a function`, if I just use `debounce()` the error is `"TypeError: Object(...) is not a function"`. I installed it correctly because it is declared in my package.json as a depencency: ` "lodash.debounce": "^4.0.8",` – Reinier68 Nov 06 '20 at 11:12
  • If you write `mounted: { console.log(debounce) }` - What does it print? – Shaya Ulman Nov 06 '20 at 11:20
  • 1
    I tested a few different possibilities, and now it prints: ƒ debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false Which leads me to think that I now imported it properly? It still doesn't log anything tho when the method is called. – Reinier68 Nov 06 '20 at 11:26
  • I think, the reason lies in the fact that `debounce(...)` returns a function, which when invoked will actually log what you expect it to log. – lacrit Nov 06 '20 at 11:41

1 Answers1

7

The issue is not with importing a single Lodash function,debounce just returns a function (a new version of the original passed function). To call the original function you need to invoke the function that debounce returns.

This is probably what you want:

<script>
import debounce from 'lodash/debounce';

export default {
  // ...
  methods: {
    origFunction() {
      console.log('I only get fired once every two seconds, max!');      
    },
  },
  computed: {
    // Create a debounced function
    // As it is a computed prop it will be cached, and not created again on every call
    debouncedFunction() {
      return debounce(this.origFunction, 2000);
    }
  },
  created() {
    this.debouncedFunction(); // Lodash will make sure thie function is called only once in every 2 seconds    
  }
}
</script>

See more in the Lodash docs.

Shaya Ulman
  • 1,299
  • 1
  • 12
  • 24