Skip to content

Commit

Permalink
feature: warn user (#163)
Browse files Browse the repository at this point in the history
  • Loading branch information
Satvik1769 authored Nov 2, 2024
1 parent 0f07d37 commit 849e71c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/components/CodeAndPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { useEffect, useMemo, useState } from "react"
import { useMutation, useQueryClient } from "react-query"
import EditorNav from "./EditorNav"
import { PreviewContent } from "./PreviewContent"

import useWarnUser from "@/hooks/use-warn-user"
interface Props {
snippet?: Snippet | null
}
Expand Down Expand Up @@ -118,6 +118,7 @@ export function CodeAndPreview({ snippet }: Props) {
}

const hasUnsavedChanges = snippet?.code !== code
useWarnUser({ hasUnsavedChanges })

if (!snippet && (urlParams.snippet_id || urlParams.should_create_snippet)) {
return (
Expand Down
23 changes: 23 additions & 0 deletions src/hooks/use-warn-user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { useEffect } from "react"
export default function useWarnUser({
hasUnsavedChanges,
}: {
hasUnsavedChanges: boolean
}) {
useEffect(() => {
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
if (hasUnsavedChanges) {
event.preventDefault()
event.returnValue = "" // Shows the confirmation dialog on reload or close if there are unsaved changes
}
}

// Attach event listeners
window.addEventListener("beforeunload", handleBeforeUnload)

// Cleanup event listeners on component unmount
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload)
}
}, [hasUnsavedChanges])
}

0 comments on commit 849e71c

Please sign in to comment.