From 16a85148579c640b346452cacc1b31fd2bb63838 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Se=CC=81bastien=20Loix?= Date: Thu, 3 Sep 2020 15:49:36 +0200 Subject: [PATCH] Fix JsonEditor: don't use hook state when component is controlled --- .../components/json_editor/json_editor.tsx | 18 ++++++++++++++++-- .../public/components/json_editor/use_json.ts | 6 +++--- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/src/plugins/es_ui_shared/public/components/json_editor/json_editor.tsx b/src/plugins/es_ui_shared/public/components/json_editor/json_editor.tsx index 56b5d0851ff6..206db5a28562 100644 --- a/src/plugins/es_ui_shared/public/components/json_editor/json_editor.tsx +++ b/src/plugins/es_ui_shared/public/components/json_editor/json_editor.tsx @@ -58,12 +58,26 @@ function JsonEditorComp({ const onEuiCodeEditorChange = useCallback( (updated: string) => { if (isControlled) { - setContent(updated); + onUpdate({ + data: { + raw: updated, + format: () => JSON.parse(updated), + }, + validate: () => { + try { + JSON.parse(updated); + return true; + } catch (e) { + return false; + } + }, + isValid: undefined, + }); } else { debouncedSetContent(updated); } }, - [isControlled, setContent, debouncedSetContent] + [isControlled, debouncedSetContent, onUpdate] ); return ( diff --git a/src/plugins/es_ui_shared/public/components/json_editor/use_json.ts b/src/plugins/es_ui_shared/public/components/json_editor/use_json.ts index a73649567c9d..47d518e6814a 100644 --- a/src/plugins/es_ui_shared/public/components/json_editor/use_json.ts +++ b/src/plugins/es_ui_shared/public/components/json_editor/use_json.ts @@ -28,7 +28,7 @@ export interface JsonEditorState { format(): T; }; validate(): boolean; - isValid: boolean; + isValid: boolean | undefined; } export type OnJsonEditorUpdateHandler = ( @@ -78,7 +78,7 @@ export const useJson = ({ }, [validate, content]); useEffect(() => { - if (!isMounted.current) { + if (!isMounted.current || isControlled) { return; } @@ -92,7 +92,7 @@ export const useJson = ({ validate, isValid, }); - }, [onUpdate, content, formatContent, validate]); + }, [onUpdate, content, formatContent, validate, isControlled]); useEffect(() => { isMounted.current = true;