Skip to content

Commit 2391dd6

Browse files
committed
useUnsaved can now take a router instance or the hook
1 parent d52ed16 commit 2391dd6

File tree

2 files changed

+9
-7
lines changed

2 files changed

+9
-7
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "react-exo-hooks",
3-
"version": "1.0.1",
3+
"version": "1.0.2",
44
"module": "index.ts",
55
"main": "dist/index.js",
66
"description": "A collection of useful hooks for data structures and logic, designed for efficiency",

src/hooks/use-unsaved.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
import { useEffect } from 'react'
2-
import type { Router } from 'next/router'
2+
import type { NextRouter, useRouter } from 'next/router'
33

44
/**
55
* Don't let a user navigate or close the page if changes aren't saved
66
* @param unsaved Are there unsaved changes?
7-
* @param nextRouter If using NextJS, the next router (prevents NextJS navigation)
7+
* @param nextRouter If using NextJS, the next router instance or hook (prevents NextJS navigation)
88
*/
9-
export function useUnsaved (unsaved?: boolean, nextRouter?: Router): void {
9+
export function useUnsaved (unsaved?: boolean, nextRouter?: NextRouter | typeof useRouter): void {
10+
const router = typeof nextRouter === 'function' ? nextRouter() : nextRouter
11+
1012
useEffect(() => {
1113
if (unsaved) {
1214
/**
@@ -23,15 +25,15 @@ export function useUnsaved (unsaved?: boolean, nextRouter?: Router): void {
2325
*/
2426
function preventUnsavedNav (url: string): void {
2527
const urlSplit = url.split('?')[0]!.split('/')
26-
if (nextRouter?.pathname.split('/').every((subroute, i) => (subroute.startsWith('[') && subroute.endsWith(']')) || subroute === urlSplit[i])) return
28+
if (router?.pathname.split('/').every((subroute, i) => (subroute.startsWith('[') && subroute.endsWith(']')) || subroute === urlSplit[i])) return
2729

2830
if (!confirm('Changes you made may not be saved.')) throw new Error('Navigation Canceled')
2931
}
3032

31-
nextRouter?.events.on('routeChangeStart', preventUnsavedNav)
33+
router?.events.on('routeChangeStart', preventUnsavedNav)
3234
window.addEventListener('beforeunload', preventUnsavedClose)
3335
return () => {
34-
nextRouter?.events.off('routeChangeStart', preventUnsavedNav)
36+
router?.events.off('routeChangeStart', preventUnsavedNav)
3537
window.removeEventListener('beforeunload', preventUnsavedClose)
3638
}
3739
}

0 commit comments

Comments
 (0)