Use debounce instead

This commit is contained in:
Ola Hungerford
2025-03-04 20:54:13 -07:00
parent 06773bb6dd
commit f9b105c0ef

View File

@@ -1,4 +1,4 @@
import { useState, useEffect } from "react"; import { useState, useEffect, useCallback, useRef } from "react";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label"; import { Label } from "@/components/ui/label";
@@ -51,6 +51,28 @@ const DynamicJsonForm = ({
JSON.stringify(value ?? generateDefaultValue(schema), null, 2), JSON.stringify(value ?? generateDefaultValue(schema), null, 2),
); );
// Create a ref to store the timeout ID
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
// Create a debounced function to update parent state
const debouncedUpdateParent = useCallback((jsonString: string) => {
// Clear any existing timeout
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
// Set a new timeout
timeoutRef.current = setTimeout(() => {
try {
const parsed = JSON.parse(jsonString);
onChange(parsed);
setJsonError(undefined);
} catch {
// Don't set error during normal typing
}
}, 300);
}, [onChange, setJsonError]);
// Update rawJsonValue when value prop changes // Update rawJsonValue when value prop changes
useEffect(() => { useEffect(() => {
if (!isJsonMode) { if (!isJsonMode) {
@@ -329,17 +351,11 @@ const DynamicJsonForm = ({
<JsonEditor <JsonEditor
value={rawJsonValue} value={rawJsonValue}
onChange={(newValue) => { onChange={(newValue) => {
// Always update local state
setRawJsonValue(newValue); setRawJsonValue(newValue);
try {
if (/^\s*[{[].*[}\]]\s*$/.test(newValue)) { // Use the debounced function to attempt parsing and updating parent
const parsed = JSON.parse(newValue); debouncedUpdateParent(newValue);
onChange(parsed);
setJsonError(undefined);
}
} catch {
// Don't set an error during typing - that will happen when the user
// tries to save or submit the form
}
}} }}
error={jsonError} error={jsonError}
/> />