Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: refactor `<PreventNavigationOnUnsavedChanges>` by extracting a `usePreventNavigationOnUnsavedChanges` hook (#43900)

Gildas Garciad571c7404ad1
diff --git a/apps/studio/components/ui-patterns/Dialogs/PreventNavigationOnUnsavedChanges.tsx b/apps/studio/components/ui-patterns/Dialogs/PreventNavigationOnUnsavedChanges.tsx
index a7e0a8f3dcc..3ea9eb30008 100644
--- a/apps/studio/components/ui-patterns/Dialogs/PreventNavigationOnUnsavedChanges.tsx
+++ b/apps/studio/components/ui-patterns/Dialogs/PreventNavigationOnUnsavedChanges.tsx
@@ -1,11 +1,8 @@
-import { useRouter } from 'next/router'
-import { useEffect, useState } from 'react'
-import { BASE_PATH } from 'lib/constants'
-
import {
DiscardChangesConfirmationDialog,
type DiscardChangesConfirmationDialogProps,
} from './DiscardChangesConfirmationDialog'
+import { usePreventNavigationOnUnsavedChanges } from '@/hooks/ui/usePreventNavigationOnUnsavedChanges'
export const PreventNavigationOnUnsavedChanges = ({
hasChanges,
@@ -14,56 +11,15 @@ export const PreventNavigationOnUnsavedChanges = ({
DiscardChangesConfirmationDialogProps,
'visible' | 'onClose' | 'onCancel'
>) => {
- const router = useRouter()
- const [navigateUrl, setNavigateUrl] = useState<string>()
- const [confirmNavigate, setConfirmNavigate] = useState(false)
-
- useEffect(() => {
- const handleBeforeUnload = (e: BeforeUnloadEvent) => {
- if (hasChanges) {
- e.preventDefault()
- e.returnValue = '' // deprecated, but older browsers still require this
- }
- }
-
- const handleBrowseAway = (url: string) => {
- if (hasChanges && !confirmNavigate) {
- setNavigateUrl(url)
- throw 'Route change declined' // Just to prevent the route change
- return
- }
- setNavigateUrl(undefined)
- }
- window.addEventListener('beforeunload', handleBeforeUnload)
- router.events.on('routeChangeStart', handleBrowseAway)
-
- return () => {
- window.removeEventListener('beforeunload', handleBeforeUnload)
- router.events.off('routeChangeStart', handleBrowseAway)
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [confirmNavigate, hasChanges])
-
- const handleCancel = () => {
- setNavigateUrl(undefined)
- }
-
- const handleClose = () => {
- setConfirmNavigate(true)
- let urlToNavigate = navigateUrl ?? '/'
- if (BASE_PATH && urlToNavigate.startsWith(BASE_PATH)) {
- urlToNavigate = urlToNavigate.slice(BASE_PATH.length) || '/'
- }
- if (!urlToNavigate.startsWith('/')) urlToNavigate = `/${urlToNavigate}`
- setNavigateUrl(undefined)
- router.push(urlToNavigate)
- }
+ const { handleCancel, handleConfirm, shouldConfirm } = usePreventNavigationOnUnsavedChanges({
+ hasChanges,
+ })
return (
<DiscardChangesConfirmationDialog
- visible={!!navigateUrl}
+ visible={shouldConfirm}
onCancel={handleCancel}
- onClose={handleClose}
+ onClose={handleConfirm}
{...props}
/>
)
diff --git a/apps/studio/hooks/ui/usePreventNavigationOnUnsavedChanges.ts b/apps/studio/hooks/ui/usePreventNavigationOnUnsavedChanges.ts
new file mode 100644
index 00000000000..8cd101bf063
--- /dev/null
+++ b/apps/studio/hooks/ui/usePreventNavigationOnUnsavedChanges.ts
@@ -0,0 +1,91 @@
+import { useRouter } from 'next/router'
+import { useEffect, useMemo, useState } from 'react'
+
+import { useStaticEffectEvent } from '../useStaticEffectEvent'
+import { BASE_PATH } from '@/lib/constants'
+
+interface UsePreventNavigationOnUnsavedChangesOptions {
+ /*
+ * Boolean indicating whether there are changes that would be lost if users navigate to another
+ * page or close the browser tab
+ */
+ hasChanges: boolean
+}
+
+interface UsePreventNavigationOnUnsavedChangesReturn {
+ /*
+ * Cancel the navigation and keep the changes
+ */
+ handleCancel: () => void
+ /*
+ * Confirm the navigation and lose the changes
+ */
+ handleConfirm: () => void
+ /*
+ * Boolean indicating whether UI to request users confirmation for the navigation should be
+ * displayed
+ */
+ shouldConfirm: boolean
+}
+
+/*
+ * Hook that prevents navigation when users could lose their changes.
+ * It prevents both NextJS and browser navigation (such as when closing the tab)
+ */
+export const usePreventNavigationOnUnsavedChanges = ({
+ hasChanges,
+}: UsePreventNavigationOnUnsavedChangesOptions): UsePreventNavigationOnUnsavedChangesReturn => {
+ const router = useRouter()
+ const [navigateUrl, setNavigateUrl] = useState<string>()
+ const [confirmNavigate, setConfirmNavigate] = useState(false)
+
+ useEffect(() => {
+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {
+ if (hasChanges) {
+ e.preventDefault()
+ e.returnValue = '' // deprecated, but older browsers still require this
+ }
+ }
+
+ const handleBrowseAway = (url: string) => {
+ if (hasChanges && !confirmNavigate) {
+ setNavigateUrl(url)
+ throw 'Route change declined' // Just to prevent the route change
+ return
+ }
+ setNavigateUrl(undefined)
+ }
+ window.addEventListener('beforeunload', handleBeforeUnload)
+ router.events.on('routeChangeStart', handleBrowseAway)
+
+ return () => {
+ window.removeEventListener('beforeunload', handleBeforeUnload)
+ router.events.off('routeChangeStart', handleBrowseAway)
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [confirmNavigate, hasChanges])
+
+ const handleCancel = useStaticEffectEvent(() => {
+ setNavigateUrl(undefined)
+ })
+
+ const handleConfirm = useStaticEffectEvent(() => {
+ setConfirmNavigate(true)
+ let urlToNavigate = navigateUrl ?? '/'
+ if (BASE_PATH && urlToNavigate.startsWith(BASE_PATH)) {
+ urlToNavigate = urlToNavigate.slice(BASE_PATH.length) || '/'
+ }
+ if (!urlToNavigate.startsWith('/')) urlToNavigate = `/${urlToNavigate}`
+ setNavigateUrl(undefined)
+ router.push(urlToNavigate)
+ })
+
+ return useMemo(
+ () => ({
+ handleCancel,
+ handleConfirm,
+ shouldConfirm: !!navigateUrl,
+ }),
+ [navigateUrl, handleCancel, handleConfirm]
+ )
+}