Skip to content

Commit 4abf0f1

Browse files
Merge pull request #163 from devtron-labs/feat/use-prompt
feat: add use prompt for refresh
2 parents 0af9f26 + b50e77f commit 4abf0f1

File tree

5 files changed

+36
-0
lines changed

5 files changed

+36
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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

src/Shared/Hooks/UsePrompt/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { default as usePrompt } from './UsePrompt'

src/Shared/Hooks/UsePrompt/types.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export interface UsePromptProps {
2+
/**
3+
* If true the prompt will be shown
4+
*/
5+
shouldPrompt: boolean
6+
}

src/Shared/Hooks/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './UsePrompt'

src/Shared/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,4 @@ export * from './constants'
2121
export * from './types'
2222
export * from './Providers'
2323
export * from './constants'
24+
export * from './Hooks'

0 commit comments

Comments
 (0)