Skip to content

Commit

Permalink
feat(client): add useOnBeforeUnload where appropriate
Browse files Browse the repository at this point in the history
  • Loading branch information
benji6 committed Nov 24, 2023
1 parent 91221b0 commit 87dad60
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
21 changes: 18 additions & 3 deletions client/src/components/pages/AddNote.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ import { ClientNote } from "../../types";
import useKeyboardSave from "../hooks/useKeyboardSave";
import { DispatchContext } from "../AppState";
import { ERRORS } from "../../constants";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useContext, useRef, useState } from "react";
import {
useBeforeUnload,
useNavigate,
useSearchParams,
} from "react-router-dom";
import { useCallback, useContext, useRef, useState } from "react";
import TagComboBox from "../shared/TagComboBox";

export default function AddNote() {
Expand Down Expand Up @@ -41,6 +45,17 @@ export default function AddNote() {

useKeyboardSave(handleSubmit);

const shouldShowSaveButton = Boolean(textAreaValue.trim());

useBeforeUnload(
useCallback(
(e) => {
if (shouldShowSaveButton) e.preventDefault();
},
[shouldShowSaveButton],
),
);

return (
<Paper.Group>
<Paper>
Expand Down Expand Up @@ -69,7 +84,7 @@ export default function AddNote() {
rows={14}
value={textAreaValue}
/>
{textAreaValue.trim() && (
{shouldShowSaveButton && (
<Button.Group>
<Button onClick={handleSubmit}>
<Icon margin="end" name="save" />
Expand Down
18 changes: 16 additions & 2 deletions client/src/components/pages/EditNote/EditNoteForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { ClientNote } from "../../../types";
import useKeyboardSave from "../../hooks/useKeyboardSave";
import { DispatchContext } from "../../AppState";
import { ERRORS } from "../../../constants";
import { useNavigate } from "react-router-dom";
import { useContext, useState } from "react";
import { useBeforeUnload, useNavigate } from "react-router-dom";
import { useCallback, useContext, useState } from "react";
import TagComboBox from "../../shared/TagComboBox";

interface Props {
Expand Down Expand Up @@ -46,6 +46,20 @@ export default function EditNoteForm({ dateCreated, note }: Props) {

useKeyboardSave(handleSubmit);

const shouldShowSaveButton = Boolean(
textAreaValue.trim() &&
(textAreaValue.trim() !== note.body ||
tagValue.trim() !== (note.tag ?? "")),
);
useBeforeUnload(
useCallback(
(e) => {
if (shouldShowSaveButton) e.preventDefault();
},
[shouldShowSaveButton],
),
);

const dateCreatedObj = new Date(note.dateCreated);
const dateUpdatedObj = new Date(note.dateUpdated);

Expand Down

0 comments on commit 87dad60

Please sign in to comment.