xnimorz/use-debounce

Callback can't return a promise

Closed this issue · 5 comments

const { callback } = useDebouncedCallback(
  async () => {
    return new Promise((r) => setTimeout(r, 3000));
  },
  300,
  { leading: true }
);

React.useEffect(() => {
    callback().then(() => console.log('yay'));
},[]);

This code will fail which is very misleading as the typing for the callback is a Promise<void>

Hi, yes callback inside useDebouncedCallback now returns a value, but it could be undefined or null. I'll fix it soon

Hi @BrendonSled
TypeScript has a problem with defining null and undefined as types:

let b: Promise<string> = undefined;
b.then((a) => 'a');

this is a valid ts code, but it's absolutely meaningless.

I'll add information to the docs, that you should check if you get undefined directly.

Hello @BrendonSled
I've published use-debounce@5.0.2 with the description, why you get undefined:
https://github.com/xnimorz/use-debounce#returned-value-from-debouncedcallback

Also, talking about further versions of the library, check the PR #83 maybe it will be more convenient

Hi, I'm going to close the issue. Feel free to reopen it or make another one if needed.

How does this fail? Seems to work. Logs yay in console https://codesandbox.io/s/intelligent-dust-9pivn?file=/src/App.js

Also what is the main real-world use-case for awaiting promses returned from a debounced function? It seems weird. What would you expect to happen if the function is called twice before the first promise resolves? Right now it calls the debounced function with the latest arguments received.

I don't know if this library should support this usecase (lodash debounce doesn't for example), but if they want to, one possibility could be a flag that would tell the function to call the debounced function with all the recieved arguments as an array. Similar to https://github.com/bjoerge/debounce-promise#with-accumulatetrue