From f9b105c0efe274259ac3a405958f9699611ced95 Mon Sep 17 00:00:00 2001 From: Ola Hungerford Date: Tue, 4 Mar 2025 20:54:13 -0700 Subject: [PATCH] Use debounce instead --- client/src/components/DynamicJsonForm.tsx | 38 ++++++++++++++++------- 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/client/src/components/DynamicJsonForm.tsx b/client/src/components/DynamicJsonForm.tsx index 8e6f8c2..0e2ee48 100644 --- a/client/src/components/DynamicJsonForm.tsx +++ b/client/src/components/DynamicJsonForm.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect } from "react"; +import { useState, useEffect, useCallback, useRef } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -51,6 +51,28 @@ const DynamicJsonForm = ({ JSON.stringify(value ?? generateDefaultValue(schema), null, 2), ); + // Create a ref to store the timeout ID + const timeoutRef = useRef>(); + + // 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 useEffect(() => { if (!isJsonMode) { @@ -329,17 +351,11 @@ const DynamicJsonForm = ({ { + // Always update local state setRawJsonValue(newValue); - try { - if (/^\s*[{[].*[}\]]\s*$/.test(newValue)) { - const parsed = JSON.parse(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 - } + + // Use the debounced function to attempt parsing and updating parent + debouncedUpdateParent(newValue); }} error={jsonError} />