diff --git a/web/hooks/use-warn-unsaved-changes.ts b/web/hooks/use-warn-unsaved-changes.ts new file mode 100644 index 00000000..b871b8b2 --- /dev/null +++ b/web/hooks/use-warn-unsaved-changes.ts @@ -0,0 +1,31 @@ +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 = () => { + 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]) +} diff --git a/web/pages/create.tsx b/web/pages/create.tsx index 7b9b2da0..d4bb3786 100644 --- a/web/pages/create.tsx +++ b/web/pages/create.tsx @@ -22,6 +22,7 @@ import { removeUndefinedProps } from 'common/util/object' import { CATEGORIES } from 'common/categories' import { ChoicesToggleGroup } from 'web/components/choices-toggle-group' import { track } from 'web/lib/service/analytics' +import { useWarnUnsavedChanges } from 'web/hooks/use-warn-unsaved-changes' export default function Create() { const [question, setQuestion] = useState('') @@ -108,6 +109,9 @@ export function NewContract(props: { question: string }) { // get days from today until the end of this year: const daysLeftInTheYear = dayjs().endOf('year').diff(dayjs(), 'day') + const hasUnsavedChanges = Boolean(question || description) + useWarnUnsavedChanges(hasUnsavedChanges) + const isValid = (outcomeType === 'BINARY' ? initialProb >= 5 && initialProb <= 95 : true) && question.length > 0 &&