predikt/oracle/web/hooks/use-warn-unsaved-changes.ts
caelum0x 2b68bde5d5 Predikt: full Polymarket-style prediction market — web + mobile + on-chain + bots
Working tree is now the canonical repo. Off-chain play-money + trustless on-chain
(FPMM AMM + CLOB via UMA settlement), AI market factory, creator/social/distribution,
mobile shell + push, one-command demo + deploy-kit. Secrets excluded (see ENV-AND-KEYS.md).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 23:29:50 +03:00

36 lines
1.1 KiB
TypeScript

import { Router } from 'next/router'
import { useEffect } from 'react'
export const useWarnUnsavedChanges = (hasUnsavedChanges: boolean) => {
useEffect(() => {
if (!hasUnsavedChanges) return
const confirmationMessage = 'Changes you made may not be saved.'
const warnUnsavedChanges = (e: BeforeUnloadEvent) => {
const event = e || window.event
event.returnValue = confirmationMessage
return confirmationMessage
}
const beforeRouteHandler = (href: string) => {
const pathname = href.split('?')[0]
// Don't warn if the user is navigating to the same page.
if (pathname === location.pathname) return
if (!confirm(confirmationMessage)) {
Router.events.emit('routeChangeError')
throw 'Abort route change. Please ignore this error.'
}
}
window.addEventListener('beforeunload', warnUnsavedChanges)
Router.events.on('routeChangeStart', beforeRouteHandler)
return () => {
window.removeEventListener('beforeunload', warnUnsavedChanges)
Router.events.off('routeChangeStart', beforeRouteHandler)
}
}, [hasUnsavedChanges])
}