Skip to content

Commit

Permalink
Site Editor: Avoid content loss when switching between editors (#41407)
Browse files Browse the repository at this point in the history
* Site Editor: Avoid content loss when switching between editors
* Remove extra comments
  • Loading branch information
Mamaduka authored May 27, 2022
1 parent 4f49007 commit 5bb2331
Showing 1 changed file with 12 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,19 @@
*/
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';

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 );
Expand All @@ -42,6 +37,7 @@ export default function CodeEditorTextArea( { value, onChange, onInput } ) {
onInput( newValue );
setStateValue( newValue );
setIsDirty( true );
valueRef.current = newValue;
};

/**
Expand All @@ -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 (
<>
<VisuallyHidden
Expand Down

0 comments on commit 5bb2331

Please sign in to comment.