Fetch all the posts from database and render for admin to see, edit and delete.
// pages/admin/posts/index
import { useState, useEffect } from "react";
import AdminLayout from "../../../components/layout/AdminLayout";
import { Row, Col, Button, List } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import Link from "next/link";
import axios from "axios";
const Posts = () => {
// state
const [loading, setLoading] = useState(false);
const [posts, setPosts] = useState([]);
useEffect(() => {
const fetchPosts = async () => {
try {
const { data } = await axios.get("/posts");
setPosts(data);
} catch (err) {
console.log(err);
}
};
fetchPosts();
}, []);
const handleEdit = async () => {
//
};
const handleDelete = async () => {
//
};
return (
<AdminLayout>
<Row>
<Col span={24}>
<Button
type="primary"
htmlType="submit"
style={{ margin: "10px 0px 10px 0" }}
>
<Link href="/admin/posts/new">
<a>
<PlusOutlined /> Add New
</a>
</Link>
</Button>
<h1>{posts?.length} Posts</h1>
<List
itemLayout="horizontal"
dataSource={posts}
renderItem={(item) => (
<List.Item
actions={[
<a onClick={() => handleEdit(item)}>edit</a>,
<a onClick={() => handleDelete(item)}>delete</a>,
]}
>
<List.Item.Meta title={item.title} />
</List.Item>
)}
/>
</Col>
</Row>
</AdminLayout>
);
};
export default Posts;
All posts route and controller function (server)
// route
router.get("/posts", posts);
// controller
export const posts = async (req, res) => {
try {
const posts = await Post.find({})
.populate("postedBy", "_id name")
.populate("categories", "_id name slug")
.sort({ createdAt: -1 })
.exec();
return res.json(posts);
} catch (err) {
console.log(err);
}
};