Skip to content

Commit

Permalink
Text Editor: Avoid content loss (#40730)
Browse files Browse the repository at this point in the history
* Text Editor: Avoid content loss

* Update method

* Fix unit tests

* Avoid code duplication

* Back to the side effects
  • Loading branch information
Mamaduka authored and gziolo committed May 6, 2022
1 parent 5fac2d7 commit 61475a6
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion packages/editor/src/components/post-text-editor/index.js
Expand Up @@ -7,7 +7,7 @@ import Textarea from 'react-autosize-textarea';
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useState } from '@wordpress/element';
import { useEffect, useState, useRef } from '@wordpress/element';
import { parse } from '@wordpress/blocks';
import { useDispatch, useSelect } from '@wordpress/data';
import { useInstanceId } from '@wordpress/compose';
Expand All @@ -29,6 +29,7 @@ export default function PostTextEditor() {
const [ value, setValue ] = useState( postContent );
const [ isDirty, setIsDirty ] = useState( false );
const instanceId = useInstanceId( PostTextEditor );
const valueRef = useRef();

if ( ! isDirty && value !== postContent ) {
setValue( postContent );
Expand Down Expand Up @@ -65,6 +66,18 @@ export default function PostTextEditor() {
}
};

useEffect( () => {
valueRef.current = value;
}, [ value ] );

// Ensure changes aren't lost when component unmounts.
useEffect( () => {
return () => {
const blocks = parse( valueRef.current );
resetEditorBlocks( blocks );
};
}, [] );

return (
<>
<VisuallyHidden
Expand Down

0 comments on commit 61475a6

Please sign in to comment.