Fix note switching to save unsaved changes before loading new note
- Added loadNewNote helper function to encapsulate note loading logic - Check for unsaved changes when switching notes - Save previous note if it has unsaved changes - Add 100ms delay before loading new note to ensure save completes - Prevents data loss when switching from unsaved note to another note - Fixes bug where new note content would overwrite unsaved changes
This commit is contained in:
@@ -53,10 +53,7 @@ export function NoteEditor({ note, onUpdateNote, fontSize }: NoteEditorProps) {
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (previousNoteIdRef.current !== null && previousNoteIdRef.current !== note?.id) {
|
||||
handleSave();
|
||||
}
|
||||
|
||||
const loadNewNote = () => {
|
||||
if (note && editor) {
|
||||
setLocalTitle(note.title);
|
||||
setLocalFavorite(note.favorite);
|
||||
@@ -74,6 +71,20 @@ export function NoteEditor({ note, onUpdateNote, fontSize }: NoteEditorProps) {
|
||||
const html = marked.parse(note.content || '', { async: false }) as string;
|
||||
editor.commands.setContent(html);
|
||||
}
|
||||
};
|
||||
|
||||
// If switching notes, save the previous note first
|
||||
if (previousNoteIdRef.current !== null && previousNoteIdRef.current !== note?.id) {
|
||||
// Save if there are unsaved changes
|
||||
if (hasUnsavedChanges && editor) {
|
||||
handleSave();
|
||||
}
|
||||
// Load new note after a brief delay to ensure save completes
|
||||
setTimeout(loadNewNote, 100);
|
||||
} else {
|
||||
// First load or same note, load immediately
|
||||
loadNewNote();
|
||||
}
|
||||
}, [note?.id, editor]);
|
||||
|
||||
const handleSave = () => {
|
||||
|
||||
Reference in New Issue
Block a user