Skip to content

Commit

Permalink
Fix JsonEditor: don't use hook state when component is controlled
Browse files Browse the repository at this point in the history
  • Loading branch information
sebelga committed Sep 3, 2020
1 parent 438d9f2 commit 16a8514
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,26 @@ function JsonEditorComp<T extends object = { [key: string]: any }>({
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 (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export interface JsonEditorState<T = { [key: string]: any }> {
format(): T;
};
validate(): boolean;
isValid: boolean;
isValid: boolean | undefined;
}

export type OnJsonEditorUpdateHandler<T = { [key: string]: any }> = (
Expand Down Expand Up @@ -78,7 +78,7 @@ export const useJson = <T extends object = { [key: string]: any }>({
}, [validate, content]);

useEffect(() => {
if (!isMounted.current) {
if (!isMounted.current || isControlled) {
return;
}

Expand All @@ -92,7 +92,7 @@ export const useJson = <T extends object = { [key: string]: any }>({
validate,
isValid,
});
}, [onUpdate, content, formatContent, validate]);
}, [onUpdate, content, formatContent, validate, isControlled]);

useEffect(() => {
isMounted.current = true;
Expand Down

0 comments on commit 16a8514

Please sign in to comment.