|
1 |
| -import { useState, useEffect } from "react"; |
| 1 | +import { useState, useEffect, useCallback, useRef } from "react"; |
2 | 2 | import { Button } from "@/components/ui/button";
|
3 | 3 | import { Input } from "@/components/ui/input";
|
4 | 4 | import { Label } from "@/components/ui/label";
|
@@ -51,6 +51,28 @@ const DynamicJsonForm = ({
|
51 | 51 | JSON.stringify(value ?? generateDefaultValue(schema), null, 2),
|
52 | 52 | );
|
53 | 53 |
|
| 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 | + |
54 | 76 | // Update rawJsonValue when value prop changes
|
55 | 77 | useEffect(() => {
|
56 | 78 | if (!isJsonMode) {
|
@@ -329,17 +351,11 @@ const DynamicJsonForm = ({
|
329 | 351 | <JsonEditor
|
330 | 352 | value={rawJsonValue}
|
331 | 353 | onChange={(newValue) => {
|
| 354 | + // Always update local state |
332 | 355 | 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); |
343 | 359 | }}
|
344 | 360 | error={jsonError}
|
345 | 361 | />
|
|
0 commit comments