Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code Editor: Commit changes upon switching editors to avoid content loss #40730

Merged
merged 5 commits into from May 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 );
mcsf marked this conversation as resolved.
Show resolved Hide resolved
resetEditorBlocks( blocks );
};
}, [] );

return (
<>
<VisuallyHidden
Expand Down