score:0

Accepted answer

the issue was importing the wrong lodash function. specifically, i was originally importing:

import { debounce } from 'lodash/fp';

which (from my partial understanding) is a wrapper that better applies to functional programming techniques.

in this case, what i needed was to import:

import { debounce } from 'lodash';

score:1

i assume the mentioned typeerror was thrown during the useeffect, since you have not provided any stack trace.

edit thanks to the comment and suggestion by @ori drori: change the delayedquery to the following:

const delayedquery = usecallback(debounce(updatequery, 500), []);

this way, you will have a memoized value of your debounced method, which will be a callback anyway, with the available cancel property.


previous answer (just for reference):

then you can try changing your useeffect to the following:

useeffect(() => {
  const query = delayedquery();
  query();
  
  // cancel the denounce on useeffect cleanup
  return query.cancel;
}, [userquery, delayedquery]);

explanation

you can have a look at the different types of your methods and callbacks. i‘ll start at the beginning:

  1. usecallback simply takes any method and returns a new method, which will simply invoke the provided method. it will match the signature of the provided method.
  2. the provided callback, in turn, is a simple arrow function, which returns a debounced method.
  3. the debounced method, according to the lodash docs, can either be called immediately, canceled or flushed.

this leads us to the following in your useeffect:

  • delayedquery is a callback.
  • you call delayedquery(), where the hook invokes the arrow function.
  • the arrow function invokes the debounce and returns its value — the debounced updatequery!
  • but: at this point, your query has not yet been invoked! moreover, since only the return type of your callback is a debounced function, there is no property delayedquery.cancel.
  • and because delayedquery.cancel == undefined, you get the mentioned typeerror.

score:2

when you call delayedquery() you return the debounced function, and not the result of calling the debounced function. since debounce returns a debounced function with the cancel method, and usecallback accepts a function, define delayedquery like this:

const delayedquery = usecallback(debounce(updatequery, 500), []);

Related Query

More Query from same tag