add usePrompt

This commit is contained in:
Dawid Wysokiński 2021-03-30 06:02:04 +02:00
parent 3d6a70e01f
commit 408870beab
3 changed files with 23 additions and 1 deletions

View File

@ -26,6 +26,7 @@ import Question from './Question';
import Navigation from './Navigation';
import Summary from './Summary';
import FixedSpinner from './FixedSpinner';
import { usePrompt } from '../../../../../../libs/hooks';
export interface TestProps {
initialQuestions: QuestionT[];
@ -44,7 +45,7 @@ const Test = ({ initialQuestions, qualification }: TestProps) => {
const [startedAt, setStartedAt] = useState(new Date());
const [endedAt, setEndedAt] = useState(new Date());
const classes = useStyles();
usePrompt(!reviewMode);
useEffect(() => {
if (headingRef.current?.scrollIntoView) {
headingRef.current?.scrollIntoView({

View File

@ -1 +1,2 @@
export * from './useCountdown';
export * from './usePrompt';

View File

@ -0,0 +1,20 @@
import { useEffect, useRef, useCallback } from 'react';
export const usePrompt = (when: boolean) => {
const whenRef = useRef(when);
useEffect(() => {
whenRef.current = when;
}, [when]);
useEffect(() => {
window.addEventListener('beforeunload', handleUnload);
}, []);
const handleUnload = useCallback((event: BeforeUnloadEvent) => {
if (whenRef.current) {
event.preventDefault();
event.returnValue = '';
}
}, []);
};