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

82 lines
3 KiB
TypeScript
Raw Normal View History

2022-03-07 01:16:08 -05:00
import { Loading, Page, Text } from "@geist-ui/core";
import { useRouter } from "next/router";
import { useCallback, useEffect, useState } from "react";
2022-03-06 19:46:59 -05:00
import Document from '../../components/document'
import Header from "../../components/header";
import UnauthenticatedHeader from "../../components/unauthenticated-header";
2022-03-06 19:46:59 -05:00
import VisibilityBadge from "../../components/visibility-badge";
import { ThemeProps } from "../_app";
2022-03-07 01:16:08 -05:00
const Post = ({ theme, changeTheme }: ThemeProps) => {
const [post, setPost] = useState<any>()
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string>()
const router = useRouter();
useEffect(() => {
async function fetchPost() {
setIsLoading(true);
if (router.query.id) {
const post = await fetch(`/api/posts/${router.query.id}`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${localStorage.getItem("drift-token")}`
}
})
2022-03-06 19:46:59 -05:00
2022-03-07 01:16:08 -05:00
if (post.ok) {
const res = await post.json()
if (res)
setPost(res)
else
setError("Post not found")
} else {
if (post.status.toString().startsWith("4")) {
router.push("/signin")
} else {
setError(post.statusText)
}
}
setIsLoading(false)
}
}
fetchPost()
}, [router, router.query.id])
2022-03-06 19:46:59 -05:00
const token = useCallback(() => {
if (typeof window !== "undefined") {
return localStorage.getItem("drift-token")
} else {
return ""
}
}, [])
2022-03-06 19:46:59 -05:00
return (
<Page>
<Page.Header>
{token() && <Header theme={theme} changeTheme={changeTheme} />}
{!token() && <UnauthenticatedHeader theme={theme} changeTheme={changeTheme} />}
2022-03-06 19:46:59 -05:00
</Page.Header>
2022-03-06 20:41:30 -05:00
<Page.Content width={"var(--main-content-width)"} margin="auto">
2022-03-07 01:16:08 -05:00
{error && <Text type="error">{error}</Text>}
{!error && (isLoading || !post?.files) && <Loading />}
{!isLoading && post && <><Text h2>{post.title} <VisibilityBadge visibility={post.visibility} /></Text>
{post.files.map(({ id, content, title }: { id: any, content: string, title: string }) => (
2022-03-06 19:46:59 -05:00
<Document
key={id}
content={content}
title={title}
editable={false}
2022-03-07 01:16:08 -05:00
initialTab={'preview'}
2022-03-06 19:46:59 -05:00
/>
2022-03-07 01:16:08 -05:00
))}
2022-03-07 01:20:23 -05:00
</>
2022-03-06 19:46:59 -05:00
}
</Page.Content>
</Page >
)
}
export default Post