Warn about unsaved changes on create page.
This commit is contained in:
parent
e4f1d7cae1
commit
730b7272ce
31
web/hooks/use-warn-unsaved-changes.ts
Normal file
31
web/hooks/use-warn-unsaved-changes.ts
Normal 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])
|
||||
}
|
|
@ -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 &&
|
||||
|
|
Loading…
Reference in New Issue
Block a user