-2

I have a list that I want to filter and return the list to display on the screen. This list is coming from an api which is returning all the data at once. My function for debounce looks like this

const debouncedFn = React.useCallback((fn: Function, delay: number) => {
let timer: any = null;
return (...args: any) => {
  clearTimeout(timer);
  timer = setTimeout(() => fn(...args), delay);
};}, []);

I am calling this inside useMemo hook like this

    let filteredItems = React.useMemo(() => {
  
    const p = debouncedFn(filterList, 400);
    console.log("p", p());
    return p();
  }, [debouncedFn]);

And the filterlist function is like this

 const filterList = () => {
    return userList.filter((x: any) => x.advertiser_name.includes(filterValue));
  };

I am expecting the filtered results inside filteredItems but it is coming undefined.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Aayushi
  • 1,736
  • 1
  • 26
  • 48
  • I think you are misunderstanding what you are console logging. `p` is the debounced function, which is a void return. There's nothing to log really. What exactly are you trying to accomplish with this code? What is the problem you are trying to use a debounced function for? – Drew Reese Apr 07 '23 at 09:05

1 Answers1

0

I'm not sure what you're trying to achieve but it doesn't sound really idiomatic in React.

You get undefined because p() actually is equivalent to calling this function:

    (...args) => {
          clearTimeout(timer);
          timer = setTimeout(() => fn(...args), delay);
        }

As you can see this function has no return value, hence it returns undefined. If you put a return value then you will see that you'll get that returned. However, it's not really what you want so I suggest rethinking your approach and using some state.

buondevid
  • 347
  • 2
  • 7