Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { useEffect } from "react";
- import { useDispatch, useSelector } from "react-redux";
- import { setPosts } from "state";
- import PostWidget from "./PostWidget";
- const PostsWidget = ({ userId, isProfile = false }) => {
- const dispatch = useDispatch();
- const posts = useSelector((state) => state.posts);
- const token = useSelector((state) => state.token);
- const getPosts = async () => {
- const response = await fetch("http://localhost:3001/posts", {
- method: "GET",
- headers: { Authorization: `Bearer ${token}` },
- });
- const data = await response.json();
- data.sort((a, b)=>{ return new Date(dateStr).getTime(a.createdAt) - new Date(dateStr).getTime(b.createdAt); })
- dispatch(setPosts({ posts: data }));
- };
- const getUserPosts = async () => {
- const response = await fetch(
- `http://localhost:3001/posts/${userId}/posts`,
- {
- method: "GET",
- headers: { Authorization: `Bearer ${token}` },
- }
- );
- const data = await response.json();
- data.sort((a, b)=>{ return new Date(dateStr).getTime(a.createdAt) - new Date(dateStr).getTime(b.createdAt); })
- dispatch(setPosts({ posts: data }));
- };
- useEffect(() => {
- if (isProfile) {
- getUserPosts();
- } else {
- getPosts();
- }
- }, []); // eslint-disable-line react-hooks/exhaustive-deps
- return (
- <>
- {posts.map(
- ({
- _id,
- userId,
- firstName,
- lastName,
- description,
- location,
- picturePath,
- userPicturePath,
- likes,
- comments,
- createdAt,
- }) => (
- <PostWidget
- key={_id}
- postId={_id}
- postUserId={userId}
- name={`${firstName} ${lastName}`}
- description={description}
- location={location}
- picturePath={picturePath}
- userPicturePath={userPicturePath}
- likes={likes}
- comments={comments}
- createdAt={createdAt} // Pass the createdAt field as a prop to the PostWidget component
- />
- )
- )}
- </>
- );
- };
- export default PostsWidget;
Advertisement
Add Comment
Please, Sign In to add comment