Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(feat) Adding useDebounce to the react utils #756

Merged
merged 11 commits into from
Sep 15, 2023
1 change: 1 addition & 0 deletions packages/framework/esm-react-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ export * from "./useStore";
export * from "./useVisit";
export * from "./useVisitTypes";
export * from "./usePagination";
export * from "./useDebounce";
43 changes: 43 additions & 0 deletions packages/framework/esm-react-utils/src/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useEffect, useState } from "react";

/**
* This hook will help us out in getting the debounced value of a state variable,
* which then makes a request to the backend.
brandones marked this conversation as resolved.
Show resolved Hide resolved
*
* For example,
*
brandones marked this conversation as resolved.
Show resolved Hide resolved
* ```tsx
* import { useDebounceValue } from "@openmrs/esm-react-utils";
brandones marked this conversation as resolved.
Show resolved Hide resolved
*
* function MyComponent() {
* const [searchTerm, setSearchTerm] = useState('');
* const debouncedSearchTerm = useDebounce(searchTerm);
* const swrResult = useSWR(`/api/search?q=${debouncedSearchTerm}`)
*
* return (
* <Search
labelText={t('search', 'Search')}
onChange={(e) => setSearchTerm(e.target.value)}
value={searchTerm}
/>
* )
brandones marked this conversation as resolved.
Show resolved Hide resolved
* }
*
* ```
*
* @param value
* @param delay number = 300
* @returns debounceValue
*/
brandones marked this conversation as resolved.
Show resolved Hide resolved
export function useDebounceValue<T>(value: T, delay: number = 300) {
brandones marked this conversation as resolved.
Show resolved Hide resolved
const [debounceValue, setDebounceValue] = useState<T>(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebounceValue(value);
}, delay);
return () => {
clearTimeout(timer);
};
}, [value, delay]);
return debounceValue;
}
Loading