mirror of
https://github.com/jnsahaj/tweakcn.git
synced 2026-08-30 18:10:28 +08:00
fix: debounce func
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useCallback, useEffect } from "react";
|
||||
import React, { useState, useEffect, useMemo } from "react";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ColorPickerProps } from "@/types";
|
||||
import { debounce } from "@/utils/debounce";
|
||||
@@ -12,13 +12,9 @@ const ColorPicker = ({ color, onChange, label }: ColorPickerProps) => {
|
||||
setLocalColor(color);
|
||||
}, [color]);
|
||||
|
||||
// Create debounced onChange handler with useCallback to maintain reference
|
||||
const debouncedOnChange = useCallback(
|
||||
(value: string) => {
|
||||
debounce(() => {
|
||||
onChange(value);
|
||||
}, 10)();
|
||||
},
|
||||
// Create a stable debounced onChange handler
|
||||
const debouncedOnChange = useMemo(
|
||||
() => debounce((value: string) => onChange(value), 20),
|
||||
[onChange]
|
||||
);
|
||||
|
||||
@@ -28,6 +24,13 @@ const ColorPicker = ({ color, onChange, label }: ColorPickerProps) => {
|
||||
debouncedOnChange(newColor);
|
||||
};
|
||||
|
||||
// Cleanup debounced function on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
debouncedOnChange.cancel();
|
||||
};
|
||||
}, [debouncedOnChange]);
|
||||
|
||||
return (
|
||||
<div className="mb-3">
|
||||
<div className="flex items-center justify-between mb-1.5">
|
||||
|
||||
+12
-3
@@ -1,10 +1,19 @@
|
||||
export function debounce(fn: (...args: any[]) => void, delay: number) {
|
||||
export function debounce<T extends (...args: any[]) => void>(
|
||||
fn: T,
|
||||
delay: number
|
||||
): T & { cancel: () => void } {
|
||||
let timeoutId: NodeJS.Timeout;
|
||||
return function (...args: any[]) {
|
||||
|
||||
const debounced = function (this: unknown, ...args: Parameters<T>) {
|
||||
clearTimeout(timeoutId);
|
||||
timeoutId = setTimeout(() => {
|
||||
// @ts-expect-error: it works
|
||||
fn.apply(this, args);
|
||||
}, delay);
|
||||
} as T & { cancel: () => void };
|
||||
|
||||
debounced.cancel = () => {
|
||||
clearTimeout(timeoutId);
|
||||
};
|
||||
|
||||
return debounced;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user