Created
May 8, 2024 10:04
-
-
Save Elvincth/6bf32a6d7662e6692572132a1dd4fb66 to your computer and use it in GitHub Desktop.
Add the "Changes you made may not be saved" warning to a Next.js app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Router } from "next/router"; | |
import { useCallback, useEffect } from "react"; | |
export const useBeforeUnload = ( | |
enabled: boolean | (() => boolean) = true, | |
message = "Changes you made may not be saved.", | |
) => { | |
const handler = useCallback( | |
(event: BeforeUnloadEvent) => { | |
const finalEnabled = typeof enabled === "function" ? enabled() : true; | |
if (!finalEnabled) { | |
return; | |
} | |
event.preventDefault(); | |
if (message) { | |
event.returnValue = message; | |
} | |
return message; | |
}, | |
[enabled, message], | |
); | |
//Handle next.js route change | |
useEffect(() => { | |
const handler = () => { | |
if (enabled && !window.confirm(message)) { | |
throw "Route Canceled"; | |
} | |
}; | |
Router.events.on("beforeHistoryChange", handler); | |
return () => { | |
Router.events.off("beforeHistoryChange", handler); | |
}; | |
}, [enabled, message]); | |
useEffect(() => { | |
if (!enabled) { | |
return; | |
} | |
window.addEventListener("beforeunload", handler); | |
return () => window.removeEventListener("beforeunload", handler); | |
}, [enabled, handler]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add the "Changes you made may not be saved" warning to a Next.js app, support next.js router