-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathBlogs.js
More file actions
59 lines (53 loc) · 1.32 KB
/
Blogs.js
File metadata and controls
59 lines (53 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import React, { useEffect, useState } from "react";
import axios from "axios";
import Blog from "./Blog";
import config from "../config";
const Blogs = () => {
const [blogs, setBlogs] = useState([]);
const [loading, setLoading] = useState(true);
const sendRequest = async () => {
try {
const res = await axios.get(`${config.BASE_URL}/api/blogs`);
return res.data;
} catch (err) {
console.error("API Error:", err.message);
return { blogs: [] };
}
};
useEffect(() => {
sendRequest().then((data) => {
if (data && data.blogs) {
setBlogs(data.blogs);
} else {
setBlogs([]);
}
setLoading(false);
});
}, []);
if (loading) {
return <p>Loading blogs...</p>;
}
return (
<div>
{blogs.length > 0 ? (
blogs.map((blog) => (
<Blog
key={blog._id}
id={blog._id}
isUser={localStorage.getItem("userId") === blog.user?._id}
title={blog.title}
desc={blog.desc}
img={blog.img}
user={blog.user?.name || "Unknown User"}
date={
blog.date ? new Date(blog.date).toLocaleDateString() : "N/A"
}
/>
))
) : (
<p>No blogs found.</p>
)}
</div>
);
};
export default Blogs;