Skip to content
Prev Previous commit
Next Next commit
fix(page): on delete success redirect to pages
  • Loading branch information
Aslam97 committed Sep 11, 2024
commit 2eb2aab7929385512a495eb7aebe25708534e1e9
19 changes: 5 additions & 14 deletions web/components/routes/page/detail/PageDetailRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ import { TopicSelector } from "@/components/custom/topic-selector"
import { Button } from "@/components/ui/button"
import { LaIcon } from "@/components/custom/la-icon"
import { useConfirm } from "@omit/react-confirm-dialog"
import { toast } from "sonner"
import { useRouter } from "next/navigation"
import { usePageActions } from "../hooks/use-page-actions"

const TITLE_PLACEHOLDER = "Untitled"

Expand Down Expand Up @@ -59,7 +59,9 @@ export function PageDetailRoute({ pageId }: { pageId: string }) {
const isMobile = useMedia("(max-width: 770px)")
const page = useCoState(PersonalPage, pageId as ID<PersonalPage>)
const router = useRouter()
const { deletePage } = usePageActions()
const confirm = useConfirm()

DeleteEmptyPage(pageId)

const handleDelete = async () => {
Expand All @@ -73,19 +75,8 @@ export function PageDetailRoute({ pageId }: { pageId: string }) {
})

if (result && me?.root.personalPages) {
try {
const index = me.root.personalPages.findIndex(item => item?.id === pageId)
if (index === -1) {
toast.error("Page not found.")
return
}

me.root.personalPages.splice(index, 1)
toast.success("Page deleted.", { position: "bottom-right" })
router.replace("/")
} catch (error) {
console.error("Delete operation fail", { error })
}
deletePage(me, pageId as ID<PersonalPage>)
router.push("/pages")
}
}

Expand Down
36 changes: 36 additions & 0 deletions web/components/routes/page/hooks/use-page-actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useCallback } from "react"
import { toast } from "sonner"
import { LaAccount, PersonalPage } from "@/lib/schema"
import { ID } from "jazz-tools"

export const usePageActions = () => {
const deletePage = useCallback((me: LaAccount, pageId: ID<PersonalPage>): void => {
if (!me.root?.personalPages) return

const index = me.root.personalPages.findIndex(item => item?.id === pageId)
if (index === -1) {
toast.error("Page not found")
return
}

const page = me.root.personalPages[index]
if (!page) {
toast.error("Page data is invalid")
return
}

try {
me.root.personalPages.splice(index, 1)

toast.success("Page deleted", {
position: "bottom-right",
description: `${page.title} has been deleted.`
})
} catch (error) {
console.error("Failed to delete page", error)
toast.error("Failed to delete page")
}
}, [])

return { deletePage }
}