From 53aa3c005b97d6295a8b6a1269c17a371f5dee2a Mon Sep 17 00:00:00 2001 From: Andrea Vesterhus Date: Tue, 28 May 2024 14:32:23 +0200 Subject: [PATCH] refactor: use memo for code state --- packages/dm-core-plugins/src/yaml/YamlPlugin.tsx | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/packages/dm-core-plugins/src/yaml/YamlPlugin.tsx b/packages/dm-core-plugins/src/yaml/YamlPlugin.tsx index ecea66188..4bd03f831 100644 --- a/packages/dm-core-plugins/src/yaml/YamlPlugin.tsx +++ b/packages/dm-core-plugins/src/yaml/YamlPlugin.tsx @@ -8,7 +8,7 @@ import { Icon, Popover, TextField, Tooltip } from '@equinor/eds-core-react' import { close, copy, edit, filter_alt, save } from '@equinor/eds-icons' import DOMPurify from 'dompurify' import hljs from 'highlight.js' -import { ChangeEvent, useEffect, useRef, useState } from 'react' +import { ChangeEvent, useMemo, useRef, useState } from 'react' import { toast } from 'react-toastify' import YAML from 'yaml' import { ActionButton, ActionsWrapper, CodeContainer } from './styles' @@ -18,8 +18,6 @@ export const YamlPlugin = (props: YamlPluginProps) => { const { idReference, config: userConfig } = props const config = { ...defaultConfig, ...userConfig } const [depth, setDepth] = useState(0) - const [asYAML, setAsYAML] = useState('') - const [asJSON, setAsJSON] = useState('') const [isEditMode, setIsEditMode] = useState(false) const [showAsJSON, setShowAsJSON] = useState( config?.languages[0] === 'json' @@ -32,12 +30,8 @@ export const YamlPlugin = (props: YamlPluginProps) => { const { document, isLoading, error, setError, updateDocument } = useDocument(idReference, depth, false, true) - useEffect(() => { - if (document) { - setAsYAML(YAML.stringify(document)) - setAsJSON(JSON.stringify(document, null, 2)) - } - }, [document]) + const asYAML = useMemo(() => YAML.stringify(document), [document]) + const asJSON = useMemo(() => JSON.stringify(document, null, 2), [document]) const copyToClipboard = () => { try { @@ -60,8 +54,6 @@ export const YamlPlugin = (props: YamlPluginProps) => { const clean = DOMPurify.sanitize(textEditor.current?.innerText || '{}') const parsedJSON = showAsJSON ? JSON.parse(clean) : YAML.parse(clean) updateDocument(parsedJSON, true).then(() => { - setAsYAML(YAML.stringify(parsedJSON)) - setAsJSON(JSON.stringify(parsedJSON, null, 2)) setIsEditMode(false) }) } catch (e) {