(noteId: string)
| 6 | import { useAuth } from './useAuth'; |
| 7 | |
| 8 | export default function useDeleteNote(noteId: string) { |
| 9 | const router = useRouter(); |
| 10 | const { user } = useAuth(); |
| 11 | |
| 12 | const openNoteIds = useStore((state) => state.openNoteIds); |
| 13 | |
| 14 | const onDeleteClick = useCallback(async () => { |
| 15 | const deletedNoteIndex = openNoteIds.findIndex( |
| 16 | (openNoteId) => openNoteId === noteId |
| 17 | ); |
| 18 | |
| 19 | if (deletedNoteIndex !== -1) { |
| 20 | // Redirect if one of the notes that was deleted was open |
| 21 | const noteIds = Object.keys(store.getState().notes); |
| 22 | // If there are other notes to redirect to, redirect to the first one |
| 23 | if (noteIds.length > 1) { |
| 24 | for (const id of noteIds) { |
| 25 | // We haven't deleted the note yet, so we need to check the id |
| 26 | if (noteId !== id) { |
| 27 | router.push(`/app/note/${id}`, undefined, { shallow: true }); |
| 28 | break; |
| 29 | } |
| 30 | } |
| 31 | } else { |
| 32 | // No note ids to redirect to, redirect to app |
| 33 | router.push('/app'); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | if (!user) { |
| 38 | return; |
| 39 | } |
| 40 | |
| 41 | await deleteBacklinks(noteId); |
| 42 | await deleteNote(user.id, noteId); |
| 43 | }, [router, user, noteId, openNoteIds]); |
| 44 | |
| 45 | return onDeleteClick; |
| 46 | } |
no test coverage detected