Skip to content

Commit f9b105c

Browse files
committed
Use debounce instead
1 parent 06773bb commit f9b105c

File tree

1 file changed

+27
-11
lines changed

1 file changed

+27
-11
lines changed

client/src/components/DynamicJsonForm.tsx

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useState, useEffect } from "react";
1+
import { useState, useEffect, useCallback, useRef } from "react";
22
import { Button } from "@/components/ui/button";
33
import { Input } from "@/components/ui/input";
44
import { Label } from "@/components/ui/label";
@@ -51,6 +51,28 @@ const DynamicJsonForm = ({
5151
JSON.stringify(value ?? generateDefaultValue(schema), null, 2),
5252
);
5353

54+
// Create a ref to store the timeout ID
55+
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
56+
57+
// Create a debounced function to update parent state
58+
const debouncedUpdateParent = useCallback((jsonString: string) => {
59+
// Clear any existing timeout
60+
if (timeoutRef.current) {
61+
clearTimeout(timeoutRef.current);
62+
}
63+
64+
// Set a new timeout
65+
timeoutRef.current = setTimeout(() => {
66+
try {
67+
const parsed = JSON.parse(jsonString);
68+
onChange(parsed);
69+
setJsonError(undefined);
70+
} catch {
71+
// Don't set error during normal typing
72+
}
73+
}, 300);
74+
}, [onChange, setJsonError]);
75+
5476
// Update rawJsonValue when value prop changes
5577
useEffect(() => {
5678
if (!isJsonMode) {
@@ -329,17 +351,11 @@ const DynamicJsonForm = ({
329351
<JsonEditor
330352
value={rawJsonValue}
331353
onChange={(newValue) => {
354+
// Always update local state
332355
setRawJsonValue(newValue);
333-
try {
334-
if (/^\s*[{[].*[}\]]\s*$/.test(newValue)) {
335-
const parsed = JSON.parse(newValue);
336-
onChange(parsed);
337-
setJsonError(undefined);
338-
}
339-
} catch {
340-
// Don't set an error during typing - that will happen when the user
341-
// tries to save or submit the form
342-
}
356+
357+
// Use the debounced function to attempt parsing and updating parent
358+
debouncedUpdateParent(newValue);
343359
}}
344360
error={jsonError}
345361
/>

0 commit comments

Comments
 (0)