Home > Blockchain >  How can I have dynamic function to pass in debounce function
How can I have dynamic function to pass in debounce function

Time:04-25

I want implement different api search in one React component and I using custom hook.

 const { request:requestOne, data, loading} = useApi(searchOneApiConfig);
 const { request:requestTwo, data, loading} = useApi(searchTwoApiConfig);
 const { request:requestThree, data, loading} = useApi(searchThreeApiConfig);

now I have to use a useCallback(debounce... for each one like:

const SearchLazyQueryOne = useCallback(debounce(requestOne, DEBOUNCED_TIME, LazyQueryConfig), []);
const SearchLazyQueryTwo = useCallback(debounce(requestTwo, DEBOUNCED_TIME, LazyQueryConfig), []); 
const SearchLazyQueryThree = useCallback(debounce(requestThree DEBOUNCED_TIME, LazyQueryConfig), []);

My question is how can I have single "searchLazyQuery" and pass dynamic request function?

(I'm using Lodash's debounce.)

CodePudding user response:

So it sounds like you want to use:

searchLazyQuery(requestTwo, /*...args*/)

...while debouncing the calls to requestTwo. That will require keeping track of the debounced functions and using the matching one (or creating one as needed).

You can store the debounced versions of the function in a Map. Here's a sketch of a hook that does that:

const useDynamicDebounce = (debouncedTime, config) => {
    // Using a ref to provide a stability guarantee on the function we return
    const ref = useRef(null);
    if (!ref.current) {
        // A map to keep track of debounced functions
        const debouncedMap = new Map();
        // The function we return
        ref.current = (fn, ...args) => {
            // Get the debounced version of this function
            let debounced = debouncedMap.get(fn);
            if (!debounced) {
                // Don't have one yet, create it
                debounced = debounce(fn, debouncedTime, config);
                debouncedMap.set(fn, debounced);
            }
            // Do the call
            return debounced(...args);
        };
    }
    return ref.current;
};

Using it in your component:

const searchLazyQuery = useDynamicDebounce(DEBOUNCED_TIME, LazyQueryConfig);

Then use searchLazyQuery(requestTwo, "args", "for", "requestTwo") (for example).

  • Related