Skip to content

Commit 12cac50

Browse files
committed
Debounce the filter changes
1 parent e473952 commit 12cac50

File tree

2 files changed

+40
-13
lines changed

2 files changed

+40
-13
lines changed

apps/webapp/app/components/runs/v3/RunFilters.tsx

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ import {
6060
TaskRunStatusCombo,
6161
} from "./TaskRunStatus";
6262
import { TaskTriggerSourceIcon } from "./TaskTriggerSource";
63+
import { useDebounceEffect } from "~/hooks/useDebounce";
6364

6465
export const RunStatus = z.enum(allTaskRunStatuses);
6566

@@ -854,18 +855,22 @@ function QueuesDropdown({
854855

855856
const fetcher = useFetcher<typeof queuesLoader>();
856857

857-
useEffect(() => {
858-
const searchParams = new URLSearchParams();
859-
searchParams.set("per_page", "25");
860-
if (searchValue) {
861-
searchParams.set("query", encodeURIComponent(searchValue));
862-
}
863-
fetcher.load(
864-
`/resources/orgs/${organization.slug}/projects/${project.slug}/env/${
865-
environment.slug
866-
}/queues?${searchParams.toString()}`
867-
);
868-
}, [searchValue]);
858+
useDebounceEffect(
859+
searchValue,
860+
(s) => {
861+
const searchParams = new URLSearchParams();
862+
searchParams.set("per_page", "25");
863+
if (searchValue) {
864+
searchParams.set("query", encodeURIComponent(s));
865+
}
866+
fetcher.load(
867+
`/resources/orgs/${organization.slug}/projects/${project.slug}/env/${
868+
environment.slug
869+
}/queues?${searchParams.toString()}`
870+
);
871+
},
872+
250
873+
);
869874

870875
const filtered = useMemo(() => {
871876
console.log(fetcher.data);

apps/webapp/app/hooks/useDebounce.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useRef } from "react";
1+
import { useEffect, useRef } from "react";
22

33
/**
44
* A function that you call with a debounce delay, the function will only be called after the delay has passed
@@ -19,3 +19,25 @@ export function useDebounce<T extends (...args: any[]) => any>(fn: T, delay: num
1919
}, delay);
2020
};
2121
}
22+
23+
/**
24+
* A function that takes in a value, function, and delay.
25+
* It will run the function with the debounced value, only if the value has changed.
26+
* It should deal with the function being passed in not being a useCallback
27+
*/
28+
export function useDebounceEffect<T>(value: T, fn: (value: T) => void, delay: number) {
29+
const fnRef = useRef(fn);
30+
31+
// Update the ref whenever the function changes
32+
fnRef.current = fn;
33+
34+
useEffect(() => {
35+
const timeout = setTimeout(() => {
36+
fnRef.current(value);
37+
}, delay);
38+
39+
return () => {
40+
clearTimeout(timeout);
41+
};
42+
}, [value, delay]); // Only depend on value and delay, not fn
43+
}

0 commit comments

Comments
 (0)