Warn about unsaved changes on create page.

This commit is contained in:
James Grugett 2022-06-15 15:12:16 -05:00
parent e4f1d7cae1
commit 730b7272ce
2 changed files with 35 additions and 0 deletions

View File

@ -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])
}

View File

@ -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 &&