Loading...
;
- }
+ if (!blog) return
+ {isAuthor && (
+
+ )}
{blog.title.toUpperCase()}
By User {blog.author_id}
diff --git a/frontend/src/utils/EditBlog.tsx b/frontend/src/utils/EditBlog.tsx
new file mode 100644
index 0000000..8850bee
--- /dev/null
+++ b/frontend/src/utils/EditBlog.tsx
@@ -0,0 +1,95 @@
+import { useEffect, useState, type FormEvent } from "react";
+
+import { useParams, useNavigate } from "react-router-dom";
+import { API_URL } from "./constants";
+import type { Blog } from "./types";
+import { countWords } from "./countWords";
+
+export function EditBlog() {
+ const { slug } = useParams<{ slug: string }>();
+ const [blog, setBlog] = useState(undefined);
+ const [title, setTitle] = useState("");
+ const [description, setDescription] = useState("");
+ const [body, setBody] = useState("");
+ const navigate = useNavigate();
+
+ useEffect(() => {
+ if (!slug) return;
+ fetch(`${API_URL}/blogs/${slug}`)
+ .then((res) => res.json())
+ .then((data: Blog) => {
+ setBlog(data);
+ setTitle(data.title);
+ setDescription(data.description);
+ setBody(data.body);
+ })
+ .catch(console.error);
+ }, [slug]);
+
+ if (!blog) return Loading…
;
+
+ async function handleSubmit(e: FormEvent) {
+ e.preventDefault();
+
+ const updatedBlog = {
+ title,
+ description,
+ body,
+ updated_at: new Date().toISOString(),
+ word_count: countWords(body),
+ version: blog ? blog.version : 1,
+ };
+
+ const res = await fetch(`${API_URL}/blogs/${slug}`, {
+ method: "PUT", // or "PATCH" if your API prefers
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(updatedBlog),
+ });
+
+ if (res.ok) {
+ navigate(`/blog/${slug}`); // go back to the viewer
+ } else {
+ console.error("Update failed:", await res.text());
+ alert("Could not update the post. See console for details.");
+ }
+ }
+
+ return (
+
+ );
+}
diff --git a/frontend/src/utils/types.ts b/frontend/src/utils/types.ts
index f4afb98..62c52f2 100644
--- a/frontend/src/utils/types.ts
+++ b/frontend/src/utils/types.ts
@@ -1,7 +1,8 @@
export interface Blog {
id: number;
title: string;
- author_id: number;
+ author_id: string;
description: string;
body: string;
+ version: number;
}