Skip to content

Instantly share code, notes, and snippets.

@Elvincth
Created May 8, 2024 10:04
Show Gist options
  • Save Elvincth/6bf32a6d7662e6692572132a1dd4fb66 to your computer and use it in GitHub Desktop.
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
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]);
};
@Elvincth
Copy link
Author

Elvincth commented May 8, 2024

Add the "Changes you made may not be saved" warning to a Next.js app, support next.js router

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment