11

I'm trying to debounce anything within an Action, it gets swallowed in one way or another...

Take this (pseudo) code:

import { debounce } from "lodash";

const actions = {
  debounceSomeLogging ({ dispatch }, text) {
    console.log("Outside debounced function.");
    debounce(function() {
      console.log("Inside debounced function.");
      dispatch("doRealThing");
    }, 1000);
  },

  doRealThing({ commit }) {
    // Whatever
  }
}

When I call the action, I see the Outside debounced function, but I can not see the other logging and the other action does not get triggered.

Anyone have experience with this and can point me in the right direction?

Titulum
  • 9,928
  • 11
  • 41
  • 79
  • 1
    debounce does not run your function but creates a new one which is when called delays the invoking of your inner function. So you need to assign the return value of debounce and call it from somewhere... – nemesv Dec 30 '18 at 11:42
  • Okay, that seemed to be the problem. Thank you a lot, I will add it as an answer. – Titulum Dec 30 '18 at 12:08

2 Answers2

14

This should definate work

import { debounce } from "lodash";

const actions = {
  debounceSomeLogging: debounce(({ dispatch }, text) => {
    console.log("Inside debounced function.");
    dispatch("doRealThing");
  }, 1000),

  doRealThing({ commit }) {
    // Whatever
  }
}
Peter Odetayo
  • 169
  • 1
  • 5
4

As nemesv pointed out in a comment, the debounce function does not call the inner function. So you need to call the debounce again, like so:

debounce(function() {
  console.log("Inside debounced function.");
  dispatch("doRealThing");
}, 1000)();

So, in short, it should look like this:

debounce(...)() instead of like this debounce(...).

Titulum
  • 9,928
  • 11
  • 41
  • 79