mirror of
https://github.com/rzmk/learnhouse.git
synced 2025-12-19 04:19:25 +00:00
feat: revamp search bar
This commit is contained in:
parent
32a59f0ffc
commit
43a1f4e8e0
2 changed files with 240 additions and 96 deletions
|
|
@ -1,26 +1,54 @@
|
|||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
// Function debouncing
|
||||
export function useDebounce<T extends (...args: any[]) => any>(
|
||||
callback: T,
|
||||
delay: number
|
||||
): T {
|
||||
): T;
|
||||
|
||||
// Value debouncing
|
||||
export function useDebounce<T>(value: T, delay: number): T;
|
||||
|
||||
// Implementation
|
||||
export function useDebounce<T>(valueOrCallback: T, delay: number): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState<T>(valueOrCallback);
|
||||
const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
// If it's a function, return a debounced version of it
|
||||
if (typeof valueOrCallback === 'function') {
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// For values, update the debounced value after the delay
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
setDebouncedValue(valueOrCallback);
|
||||
}, delay);
|
||||
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
}, [valueOrCallback, delay]);
|
||||
|
||||
return ((...args: Parameters<T>) => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
// If it's a function, return a debounced version
|
||||
if (typeof valueOrCallback === 'function') {
|
||||
return ((...args: any[]) => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
callback(...args);
|
||||
}, delay);
|
||||
}) as T;
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
(valueOrCallback as Function)(...args);
|
||||
}, delay);
|
||||
}) as T;
|
||||
}
|
||||
|
||||
// For values, return the debounced value
|
||||
return debouncedValue;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue