CoastalCommitsPastes/client/pages/post/protected/[id].tsx

93 lines
1.8 KiB
TypeScript
Raw Normal View History

2022-04-09 20:48:19 -04:00
import { Page, useToasts } from "@geist-ui/core"
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
import type { Post } from "@lib/types"
import PasswordModal from "@components/new-post/password-modal"
import { useEffect, useState } from "react"
import { useRouter } from "next/router"
import Cookies from "js-cookie"
import PostPage from "@components/post-page"
2022-03-21 21:51:19 -04:00
const Post = () => {
2022-04-09 20:48:19 -04:00
const [isPasswordModalOpen, setIsPasswordModalOpen] = useState(true)
const [post, setPost] = useState<Post>()
const router = useRouter()
const { setToast } = useToasts()
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
useEffect(() => {
if (router.isReady) {
const fetchPostWithAuth = async () => {
const resp = await fetch(`/server-api/posts/${router.query.id}`, {
headers: {
Authorization: `Bearer ${Cookies.get("drift-token")}`
}
})
if (!resp.ok) return
const post = await resp.json()
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
if (!post) return
setPost(post)
}
fetchPostWithAuth()
}
}, [router.isReady, router.query.id])
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
const onSubmit = async (password: string) => {
const res = await fetch(
`/server-api/posts/${router.query.id}?password=${password}`,
{
method: "GET",
headers: {
"Content-Type": "application/json"
}
}
)
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
if (!res.ok) {
setToast({
type: "error",
text: "Wrong password"
})
return
}
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
const data = await res.json()
if (data) {
if (data.error) {
setToast({
text: data.error,
type: "error"
})
} else {
setPost(data)
setIsPasswordModalOpen(false)
}
}
}
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
const onClose = () => {
setIsPasswordModalOpen(false)
router.push("/")
}
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
if (!router.isReady) {
return <></>
}
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
if (!post) {
return (
<Page>
<PasswordModal
creating={false}
onClose={onClose}
onSubmit={onSubmit}
isOpen={isPasswordModalOpen}
/>
</Page>
)
}
2022-03-21 21:51:19 -04:00
2022-04-09 20:48:19 -04:00
return <PostPage post={post} />
2022-03-21 21:51:19 -04:00
}
export default Post