import React, { useRef, useEffect, useState, useCallback } from "react"; import { Editor } from "@tinymce/tinymce-react"; function CustomEditor(props) { const editorRef = useRef(null); const [isEditorReady, setIsEditorReady] = useState(false); const [currentContent, setCurrentContent] = useState(props.initialData || ""); const isUserTypingRef = useRef(false); // Handle editor initialization const handleInit = useCallback((evt, editor) => { editorRef.current = editor; setIsEditorReady(true); // Set initial content immediately when editor is ready if (props.initialData) { editor.setContent(props.initialData); setCurrentContent(props.initialData); } // Simple onChange handler editor.on('change', () => { isUserTypingRef.current = true; // Mark that user is typing const content = editor.getContent(); setCurrentContent(content); if (props.onChange) { props.onChange(content); } // Reset typing flag after a short delay setTimeout(() => { isUserTypingRef.current = false; }, 100); }); }, [props.initialData, props.onChange]); // Watch for changes in initialData prop (from external sources like setValue) useEffect(() => { if (props.initialData !== currentContent && !isUserTypingRef.current) { setCurrentContent(props.initialData || ""); // Update editor content if editor is ready if (editorRef.current && isEditorReady) { editorRef.current.setContent(props.initialData || ""); } } }, [props.initialData, isEditorReady]); // Removed currentContent from dependency // Handle initial data when editor becomes ready (only for initialization) useEffect(() => { if (isEditorReady && props.initialData && editorRef.current && !isUserTypingRef.current) { editorRef.current.setContent(props.initialData); setCurrentContent(props.initialData); } }, [isEditorReady]); // Only depend on isEditorReady, not currentContent return ( ); } export default CustomEditor;