feat: ability to add and view blogs for a user
This commit is contained in:
+182
-5
@@ -14,7 +14,6 @@ import {
|
||||
} from "react-router-dom";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { BlogViewer } from "./utils/BlogViewer";
|
||||
import { BlogList } from "./utils/BlogList";
|
||||
import { RequireAdmin } from "./utils/RouteGuard";
|
||||
import { AdminPage } from "./utils/AdminPage";
|
||||
import Unauthorized from "./utils/UnauthorizedPage";
|
||||
@@ -26,6 +25,8 @@ import {
|
||||
FaSun,
|
||||
FaMoon,
|
||||
} from "react-icons/fa";
|
||||
import type { Blog } from "./utils/types";
|
||||
import { countWords } from "./utils/countWords";
|
||||
|
||||
// Base API URL from env
|
||||
const API_URL = import.meta.env.VITE_API_URL || "http://localhost:8000";
|
||||
@@ -33,7 +34,7 @@ const API_URL = import.meta.env.VITE_API_URL || "http://localhost:8000";
|
||||
// Auth Context
|
||||
interface AuthContextProps {
|
||||
isAuthenticated: boolean;
|
||||
login: (token: string) => void;
|
||||
login: (token: string, user_id: number) => void;
|
||||
logout: () => void;
|
||||
}
|
||||
const AuthContext = createContext<AuthContextProps>({
|
||||
@@ -54,8 +55,9 @@ const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
setIsAuthenticated(!!token);
|
||||
}, []);
|
||||
|
||||
const login = (token: string) => {
|
||||
const login = (token: string, user_id: number) => {
|
||||
localStorage.setItem("token", token);
|
||||
localStorage.setItem("user_id", user_id.toString());
|
||||
setIsAuthenticated(true);
|
||||
};
|
||||
|
||||
@@ -72,6 +74,179 @@ const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
||||
);
|
||||
};
|
||||
|
||||
function BlogPage() {
|
||||
const { isAuthenticated } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [blogs, setBlogs] = useState<Blog[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
fetch(`${API_URL}/blogs`)
|
||||
.then((res) => res.json())
|
||||
.then((data: Blog[]) => setBlogs(data))
|
||||
.catch((err) => console.error(err));
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex justify-end mb-4">
|
||||
<button
|
||||
onClick={() =>
|
||||
isAuthenticated ? navigate("/create") : navigate("/signin")
|
||||
}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
|
||||
>
|
||||
Create
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
{blogs.map((blog) => (
|
||||
<Link
|
||||
key={blog.id}
|
||||
to={`/blog/${blog.id}`}
|
||||
className="block p-4 border rounded hover:bg-gray-100 dark:hover:bg-gray-800"
|
||||
>
|
||||
<h3 className="text-xl font-semibold">{blog.title}</h3>
|
||||
<p className="text-sm text-gray-500">By {blog.author_id}</p>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Page for creating a blog post
|
||||
function CreateBlog() {
|
||||
const [fileName, setFileName] = useState<string>("");
|
||||
const [title, setTitle] = useState<string>("");
|
||||
const username = localStorage.getItem("user_id") || "";
|
||||
const [author, setAuthor] = useState<string>(username);
|
||||
const [description, setDescription] = useState<string>("");
|
||||
const [content, setContent] = useState<string>("");
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const text = reader.result as string;
|
||||
setContent(text);
|
||||
setFileName(file.name);
|
||||
const baseName = file.name.replace(/\.[^.]+$/, "");
|
||||
setTitle(baseName);
|
||||
setAuthor(username);
|
||||
};
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
// Stubbed API call
|
||||
try {
|
||||
const body = {
|
||||
title: title,
|
||||
author_id: localStorage.getItem("user_id"),
|
||||
description: description,
|
||||
body: content,
|
||||
created_at: new Date(Date.now()).toISOString(),
|
||||
updated_at: new Date(Date.now()).toISOString(),
|
||||
published_at: new Date(Date.now()).toISOString(),
|
||||
word_count: countWords(content),
|
||||
version: 1,
|
||||
read_time: 0,
|
||||
language: "US",
|
||||
};
|
||||
const res = await fetch(`${API_URL}/blogs`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
alert(res);
|
||||
navigate("/blog");
|
||||
} catch (err: any) {
|
||||
alert(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-xl mx-auto py-10 space-y-6">
|
||||
<h2 className="text-2xl font-bold">Create Post</h2>
|
||||
<div className="flex space-x-4">
|
||||
<label className="px-4 py-2 bg-gray-200 dark:bg-gray-700 rounded cursor-pointer hover:bg-gray-300 dark:hover:bg-gray-600">
|
||||
Upload File
|
||||
<input
|
||||
type="file"
|
||||
accept=".txt,.md"
|
||||
onChange={handleFile}
|
||||
className="hidden"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{fileName && (
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label htmlFor="title" className="block text-sm font-medium mb-1">
|
||||
Title
|
||||
</label>
|
||||
<input
|
||||
id="title"
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
className="w-full border border-gray-300 dark:border-gray-600 rounded px-3 py-2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="author" className="block text-sm font-medium mb-1">
|
||||
Author
|
||||
</label>
|
||||
<input
|
||||
id="author"
|
||||
type="text"
|
||||
value={author}
|
||||
onChange={(e) => setAuthor(e.target.value)}
|
||||
className="w-full border border-gray-300 dark:border-gray-600 rounded px-3 py-2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label
|
||||
htmlFor="description"
|
||||
className="block text-sm font-medium mb-1"
|
||||
>
|
||||
Description
|
||||
</label>
|
||||
<input
|
||||
id="description"
|
||||
type="text"
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
className="w-full border border-gray-300 dark:border-gray-600 rounded px-3 py-2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label htmlFor="content" className="block text-sm font-medium mb-1">
|
||||
Content
|
||||
</label>
|
||||
<textarea
|
||||
id="content"
|
||||
rows={10}
|
||||
value={content}
|
||||
onChange={(e) => setContent(e.target.value)}
|
||||
className="w-full border border-gray-300 dark:border-gray-600 rounded px-3 py-2 max-h-96 overflow-y-auto resize-none"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
|
||||
>
|
||||
Submit
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
// Initialize theme from localStorage or default to light
|
||||
const [darkMode, setDarkMode] = useState<boolean>(() => {
|
||||
@@ -100,7 +275,7 @@ function App() {
|
||||
<div className="p-4">
|
||||
<Routes>
|
||||
<Route path="/" element={<LandingPage />} />
|
||||
<Route path="/blog" element={<BlogList />} />
|
||||
<Route path="/blog" element={<BlogPage />} />
|
||||
<Route path="/blog/:slug" element={<BlogViewer />} />
|
||||
<Route path="/about" element={<About />} />
|
||||
<Route path="/contact" element={<Contact />} />
|
||||
@@ -116,6 +291,7 @@ function App() {
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/signin" element={<SignIn />} />
|
||||
<Route path="/profile" element={<Profile />} />
|
||||
<Route path="/create" element={<CreateBlog />} />
|
||||
</Routes>
|
||||
</div>
|
||||
</div>
|
||||
@@ -483,7 +659,8 @@ function SignIn() {
|
||||
}
|
||||
|
||||
const tokenData = await response.json();
|
||||
login(tokenData.access_token);
|
||||
alert(response);
|
||||
login(tokenData.access_token, tokenData.user_id);
|
||||
navigate("/");
|
||||
} catch (err: any) {
|
||||
alert(err.message);
|
||||
|
||||
Reference in New Issue
Block a user