Skip to content

Commit

Permalink
Hoist check to top of effect in useUnsavedChanges
Browse files Browse the repository at this point in the history
Per PR feedback [1], simplify control flow in effect body by using an early
return.

[1] #9098 (comment)
  • Loading branch information
robertknight committed Nov 20, 2024
1 parent fba1d90 commit e0a8a3c
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions h/static/scripts/group-forms/utils/unsaved-changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,24 @@ export function hasUnsavedChanges() {
* @param hasUnsavedChanges - True if current component has unsaved changes
* @param window_ - Test seam
*/
export function useUnsavedChanges(hasUnsavedData: boolean, window_ = window) {
export function useUnsavedChanges(
hasUnsavedChanges: boolean,
window_ = window,
) {
useEffect(() => {
if (hasUnsavedData) {
unsavedCount += 1;
if (unsavedCount === 1) {
window_.addEventListener('beforeunload', preventUnload);
}
if (!hasUnsavedChanges) {
return () => {};
}

unsavedCount += 1;
if (unsavedCount === 1) {
window_.addEventListener('beforeunload', preventUnload);
}
return () => {
if (hasUnsavedData) {
unsavedCount -= 1;
if (unsavedCount === 0) {
window_.removeEventListener('beforeunload', preventUnload);
}
unsavedCount -= 1;
if (unsavedCount === 0) {
window_.removeEventListener('beforeunload', preventUnload);
}
};
}, [hasUnsavedData, window_]);
}, [hasUnsavedChanges, window_]);
}

0 comments on commit e0a8a3c

Please sign in to comment.