File tree Expand file tree Collapse file tree 5 files changed +36
-0
lines changed Expand file tree Collapse file tree 5 files changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ import { useCallback , useEffect } from 'react'
2
+ import { UsePromptProps } from './types'
3
+
4
+ /**
5
+ * Hook that shows a prompt when shouldPrompt is true and the user tries to leave the page through refresh
6
+ * Meant to be used alongside the Prompt component from react-router-dom
7
+ */
8
+ const usePrompt = ( { shouldPrompt } : UsePromptProps ) => {
9
+ const handlePageLeave = useCallback (
10
+ ( e : BeforeUnloadEvent ) => {
11
+ if ( shouldPrompt ) {
12
+ e . preventDefault ( )
13
+ }
14
+ } ,
15
+ [ shouldPrompt ] ,
16
+ )
17
+
18
+ useEffect ( ( ) => {
19
+ window . addEventListener ( 'beforeunload' , handlePageLeave )
20
+
21
+ return ( ) => {
22
+ window . removeEventListener ( 'beforeunload' , handlePageLeave )
23
+ }
24
+ } , [ handlePageLeave ] )
25
+ }
26
+
27
+ export default usePrompt
Original file line number Diff line number Diff line change
1
+ export { default as usePrompt } from './UsePrompt'
Original file line number Diff line number Diff line change
1
+ export interface UsePromptProps {
2
+ /**
3
+ * If true the prompt will be shown
4
+ */
5
+ shouldPrompt : boolean
6
+ }
Original file line number Diff line number Diff line change
1
+ export * from './UsePrompt'
Original file line number Diff line number Diff line change @@ -21,3 +21,4 @@ export * from './constants'
21
21
export * from './types'
22
22
export * from './Providers'
23
23
export * from './constants'
24
+ export * from './Hooks'
You can’t perform that action at this time.
0 commit comments