From 5bb2331e0ddfadf9a9587d152e78a7af22590565 Mon Sep 17 00:00:00 2001 From: George Mamadashvili Date: Fri, 27 May 2022 19:17:39 +0400 Subject: [PATCH] Site Editor: Avoid content loss when switching between editors (#41407) * Site Editor: Avoid content loss when switching between editors * Remove extra comments --- .../code-editor/code-editor-text-area.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/packages/edit-site/src/components/code-editor/code-editor-text-area.js b/packages/edit-site/src/components/code-editor/code-editor-text-area.js index 69fd848b1f724d..1a907ca8e59f68 100644 --- a/packages/edit-site/src/components/code-editor/code-editor-text-area.js +++ b/packages/edit-site/src/components/code-editor/code-editor-text-area.js @@ -3,17 +3,11 @@ */ import Textarea from 'react-autosize-textarea'; -/** - * WordPress dependencies - */ -/** - * WordPress dependencies - */ /** * WordPress dependencies */ import { __ } from '@wordpress/i18n'; -import { useState } from '@wordpress/element'; +import { useEffect, useState, useRef } from '@wordpress/element'; import { useInstanceId } from '@wordpress/compose'; import { VisuallyHidden } from '@wordpress/components'; @@ -21,6 +15,7 @@ export default function CodeEditorTextArea( { value, onChange, onInput } ) { const [ stateValue, setStateValue ] = useState( value ); const [ isDirty, setIsDirty ] = useState( false ); const instanceId = useInstanceId( CodeEditorTextArea ); + const valueRef = useRef(); if ( ! isDirty && stateValue !== value ) { setStateValue( value ); @@ -42,6 +37,7 @@ export default function CodeEditorTextArea( { value, onChange, onInput } ) { onInput( newValue ); setStateValue( newValue ); setIsDirty( true ); + valueRef.current = newValue; }; /** @@ -56,6 +52,15 @@ export default function CodeEditorTextArea( { value, onChange, onInput } ) { } }; + // Ensure changes aren't lost when component unmounts. + useEffect( () => { + return () => { + if ( valueRef.current ) { + onChange( valueRef.current ); + } + }; + }, [] ); + return ( <>